Extra Extra! explainer


#1

Aim of the puzzle: Use .lastIndexOf() to find the last index of an element in an array.
Walk through of solution: The array cart has been imported from additional code. The array looks like this:
['flour', 'milk', 'milk', 'eggs']
The console.log(cart) line will print this array to the console so you can take a look.

For this puzzle, you will use .lastIndexOf() to find the index of the 2nd ‘milk’ and store it to the variable index. To complete the puzzle, add the string 'milk' inside the parentheses of .lastIndexOf().

.lastIndexOf() is similar to .indexOf(), except it searches backwards from the end of the array and returns the index number of the element it is searching for. In this puzzle, because there are 2 milks in the array, it will return the index of the 2nd one, as that will be the first “milk” it finds when it searches backwards from the end of cart.

If .lastIndexOf() can not find the element it is searching for, it will return -1.

Sample code solution:

import { cart } from 'grasshopper.store';
console.log(cart);
let index = cart.lastIndexOf('milk');
console.log('The extra item is at index: ' + index);

Javascript Concepts: lastIndexOf(), indexOf(), Array Indices, Array Methods, Variable Declarations with Let, Console


#2