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

yoav green
yoav green
8,611 Points

why can we use .map() in the first example?

i understand the logic of reduce and and map, but it's blurry to me when should i use each of these methods. thanks

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,735 Points

We use map when we have a list and we want to produce another list with some modification of each element.

const letters = ['a', 'b', 'c'];

const upperCaseLetters = letters.map(letter => letter.toUpperCase()); // [ 'A', 'B', 'C' ]

We use reduce when we have a list and we want to distill it into one object according to some logic.

const lettersSmushedTogether = letters.reduce((acc, curr) => {
    return acc + curr;
}, "") // "abc"

The confusing thing in the example in the video is that the object he's reducing the array into is... an array. But he took a two-dimensional array (an array of arrays) and distilled it down into a one-dimensional array.

const twoDimensionalLetters = [
    ['a', 'b', 'c'],
    ['d', 'e', 'f'],
    ['g', 'h', 'i']
];

const oneDimensionalLetters = twoDimensionalLetters.reduce((acc, curr) => {
    return [...acc, ...curr];
}, []) // [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' ]

I used the spread operator just as in the video.