Nut Free explainer

The aim of this puzzle:

Use the .filter() array method to create a new array that contains only certain items from another array.

Walkthrough of the solution:

The .filter() method takes a function as an argument (also known as a callback function) and iterates through an array using each item as the argument for the callback (or test). If the callback returns true for an item, then that item has passed the test and is copied into a new array. The original array is not modified.

The first line of code imports an array from additional code, iceCreams, so it can be used in this puzzle.

Next, the nutAllergy function is declared. It takes one argument, flavor, and returns that flavor if it is not 'pistachio'. This function is the callback/test that we will use in the .filter() method later on in our code.

Below the nutAllergy function, the nutFree variable is declared. In the code that you start off with, nutFree is the same as the iceCreams array. In this puzzle, you’ll use the .filter() method to change nutFree into an array of flavors from iceCreams that pass the nutFree test.

To complete the puzzle, add the .filter(nutAllergy) method after iceCreams. Now, the nutFree array will contain only items from the iceCreams array that pass the nutFree test.

After the nutFree variable declaration, the for...of loop will log each item in the nutFree array to the console. Without this piece of code, we wouldn’t be able to see the change from an unfiltered iceCreams array to an array that has been filtered to exclude 'pistachio'.

Sample code solution:

(Tap below to reveal)

import { iceCreams } from 'grasshopper.treats';

function nutAllergy(flavor) {
  return flavor !== 'pistachio';

let nutFree = iceCreams.filter(nutAllergy);

for (let flavors of nutFree) {

JavaScript Concepts: Array Methods, .filter(), Variable Declarations with Let, For…of Loops, Function Declarations, Imports, console.log()
Additional Code (hidden code that runs before the puzzle’s code):

let iceCreams = ['vanilla', 'chocolate', 'cookies and cream', 'cookie dough', 'mint chocolate chip', 'pistachio', 'coffee']
1 Like