Aim of the puzzle: Use indexing to access the item neighboring another item in an array.
Walk through of solution:
The getNeighbor()
function will take an array and an index, and return the item in the array that is next to the index.
To start, add 2 parameters to the function. Name them something like arr
and i
so they don’t get confused with the array
and index
variables that are imported into the puzzle.
Inside the function, create a variable to store the neighboring index. Give it a value of index + 1
Next, return the neighboring item from the function.
Finally, inside the console.log()
at the bottom of the code, add array
and index
as arguments to the function.
Sample code solution:
import { array, index } from 'grasshopper.arrayFactory';
function getNeighbor (arr, i){
let neighbor = i + 1
return arr[neighbor]
}
console.log('The neighbor to ' + array[index] + ' is ' + getNeighbor(array,index))
Javascript Concepts: Arrays, Indexing, .length
, Functions, Local Variables, Return Statement
Additional Code (hidden code that runs before the puzzle’s code):
const list = [
['first_item', 'second_item','third_item', 'fourth_item', 'fifth_item', 'sixth_item', 'seventh_item', 'eighth_item', 'ninth_item', 'tenth_item']
];
const numbers = [0,1,2,3,4,5,6,7,8]
let array =pickRandom(list);
let index = pickRandom(numbers);