Won't You Be My Neighbor? explainer

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

1 Like

I tried to write

return arr[neighbor]

But it’s impossible
S. O Android

Hey there,

There are 2 separate keys on the keyboard that look like [], an orange and a purple one. You’ll need to use the purple one.

The orange one is used to create a new array, and in the app will look like this when it is added to the code:

[
 ___,
]

The purple one is used to access an item in an array or an object property in bracket notation. This is the one you want to use here.

When added to the code, it will look like this:

[__]

We’re working on making the difference between these 2 keys more clear in the app, as it is understandably a bit confusing.

Hope this helps!
Ben

it works! , thanks :smile:

1 Like