Milk Mistake explainer

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 '';
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
Additional Code (hidden code that runs before the puzzle’s code):

let cart = ['flour', 'milk', 'milk', 'eggs']
1 Like

I happened to notice that in the instructions for this puzzle, it says to “add” the value given. When I tried this, it failed. I was only able to pass this exercise by replacement. I hope this helps!


Hey there, thanks for flagging!

I agree that this phrasing is a bit misleading. It would be more appropriate to say "Replace 'eggs' with 'milk'". We’ll make sure this gets changed for our next release.


1 Like

Glad to help grasshopper_ben!

If you happen to know a way I may be able to master coding from home, I would dearly appreciate the opportunity.

Your grasshopper app is inspirational. I loved it and understand coding better than I ever thought possible. The playground is wonderful!

Thank you for helping me find my niche!

Kind regards,

Devin Hansford

Hey there!

I answered a similar question in this thread. Perhaps this can answer some of your questions. Also, check out this post, which also has some great tips.

Let me know if you have any further questions, and I’ll be happy to answer them!


Since the index count starts from 0, why the last index of result is not 1 but 2?