Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Array Iteration Methods Combining Array Methods Nested Data and Additional Exploration

a question about reduce with spread operator

lets say we have this multi-demsional arr:

const movies = [
  ['The Day the Earth Stood Still', 'Superman', 'Ghostbusters'],
  ['Finding Dory'],
  ['Jaws', 'On the Waterfront']

and the solution :

conactWithSpread = movies.reduce((myArr,bookTitle) => [...myArr,...bookTitle],[]);
console.log("Here with spread:",conactWithSpread);

which will print :

  'The Iliad',
  'The Brothers Karamazov',
  'Tenth of December',
  'Cloud Atlas',
  'One Hundred Years of Solitude',

why would i need to add ...myArr if the ...bookTile is refercing the elements in the arr?

1 Answer

Steven Parker
Steven Parker
228,991 Points

The "reduce" function builds the result item by item, and the first argument ("myArr" in this case) is the accumulator for the result.

So for each item, "...myArr" represents all the titles seen so far, and "...bookTitle" represents the titles in the current item. By replacing "myArr" with "[...myArr, ...bookTitle]", the new titles are effectively added onto the existing collection. That way, when the function is complete, the resulting array will contain all the titles from all the sub-arrays of the original.

You can also omit the final argument here, since the first item will be a suitable starting value for the accumulator.

But there's something odd about this example, as the output shown contains entirely different titles than the ones present in the original array :open_mouth::exclamation: