Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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',
  'Candide'
]

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

1 Answer

Steven Parker
Steven Parker
210,867 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: