Aim of the puzzle: Use the spread operator (...
) to copy the elements of an array into another array.
Walk through of solution:
The first line of code in this puzzle imports 3 arrays from additional code, fiction
, nonFiction
, and poetry
, so they can be used in this puzzle.
The allBooks
variable declaration is a new array that will use the spread operator to copy the elements of each of the 3 arrays.
To complete the puzzle, add the spread operator before nonFiction
and poetry
.
What happens if we don’t use the spread operator?
let arrayOne = [1, 2, 3];
let arrayTwo = [arrayOne, 4, 5, 6]
Without the spread operator, all of arrayOne
is in arrayTwo[0]
. In other words, arrayTwo
looks like
[[1, 2, 3], 4, 5, 6]
instead of [1, 2, 3, 4, 5, 6]
. This is called nesting. Without the spread operator, arrayOne
becomes nested inside arrayTwo
.
Sample code solution:
import { fiction, nonFiction, poetry } from 'grasshopper.books';
let allBooks = [...fiction, ...nonFiction, ...poetry];
for (let book of allBooks) {
console.log(book.title + ' by ' + book.author);
}
Javascript Concepts: Arrays, Spread Operator,
Additional Code (hidden code that runs before the puzzle’s code):
const poetry= [{ title: 'Death of a Naturalist', author: 'Seamus Heaney' }, { title: 'Omeros', author: 'Derek Walcott' }];
const fiction= [{ title: 'Beloved', author: 'Toni Morrison' }, { title: 'Dubliners', author: 'James Joyce' }];
const nonFiction= [{ title: 'Down and Out in Paris and London', author: 'George Orwell' }, { title: 'A Distant Mirror', author: 'Barbara Tuchman'}];