Breakfast of Champions explainer

The aim of this puzzle: Find the index of your favorite cereal.

Walkthrough of the solution: The bestcereals variable stores a list of strings. To check if the favorite cereal, 'ant bran' is on the list, we can use bestCereals.includes(favorite). If it is on the list, we want to output its ranking. To get the index number of an array value, you can use the .indexOf() method. It will search the array starting from the beginning, and as soon as it finds the value, it returns the index of that value in the array. If it reaches the end of the array and the value wasn’t included, then it returns the number -1.

To get the index of the favorite, you replace the 'mosquito bits' string with the favorite variable.

Sample code solution:
(Tap below to reveal)

import { bestCereals } from '';

let favorite = 'ant bran';

    'Not on the list.');

JavaScript Concepts: Conditionals (ternary statement), console.log(), import, .includes(), indexOf()
Additional Code (hidden code that runs before the puzzle’s code):

let bestCereals = [
        'grasshopper crisp',
        'butterfly puffs',
        'dragonfly flakes',
        'ant bran',
        'moth balls'
1 Like

What if there were more than one instance of the item being searched for in the array - would .includes() return the index of each instance? Or only the index of the first instance?

Array.includes() just returns true if the array contains the specified item or false if it does not.

Array.indexOf() will return the index of the 1st instance if there are multiple.

I recommend checking out the document for array methods on MDN. It’s a great resource for learning.

1 Like

Thanks for that precise answer. Although I am realising that ultimately grasshopper learners need to graduate to looking things up for themselves on resources like that.

I’ve now been through Fundamentals I & II, twice each, copy-pasting notes to a document the second time through for future reference. I completed the Interviewing course, but the last half of that was getting over my head. Now I’m doing the Arrays course, which seems fairly straightforward.

The challenge seems to be finding material which pushes you without being totally incomprehensible!


What do you mean by saying : " If it reaches the end of the array and the value wasn’t included, then it returns the number -1 ."
Can you explain more ? What happen when it return the number '-1’ ?

I’m trying to recreate this code in the playground but the program do not allow me to use if…else or ternary operator inside the log() parentheses.

I had the same situation but during the Google Interview chapter I tried to recreate all the puzzles in the playground and finally I got the understanding of all those methods, of course I had spent a lot of time but it worth it.