Fruit Basket explainer


#1

The aim of this puzzle: Use the spread operator (...) to combine items from separate arrays into a new array.

Walkthrough of the solution: The first line of code imports 2 arrays from additional code, appleVarieties and pearVarieties, so they can be used in this puzzle.

Next, the fruitBasket variable is declared. In the code that you start off with, fruitBasket is an array containing two sub-arrays: appleVarieties and pearVarieties. Printed, it looks like this:

[
  [Fuji, Pink Lady, Granny Smith],
  [Bosc, Red Anjou]
]

When an array is inside of another array, it is called a nested array. In this puzzle, you’ll use to the spread operator (...) to change fruitBasket into an array that contains the items from both appleVarieties and pearVarieties but is not nested.

To complete the puzzle, add the spread operator (...) before appleVarieties and pearVarieties. Now, when printed, fruitBasket looks like this: [Fuji, Pink Lady, Granny Smith, Bosc, Red Anjou]. It is no longer a nested array.

After the fruitBasket variable declaration, the for...of loop logs each item in the fruitBasket array to the console. Without this piece of code, we wouldn’t be able to see the change from a nested array to one that is no longer nested when the spread operator (...) is used.

Sample code solution:
(Tap below to reveal)

import { appleVarieties, pearVarieties } from 'grasshopper.orchard';

let fruitBasket = [
  ...appleVarieties,
  ...pearVarieties
];

for (var fruit of fruitBasket) {
  console.log(fruit);
}

JavaScript Concepts: Arrays, Spread Operator, For…of Loops, console.log(), Imports, Variable Declarations (let)