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

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
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,702 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.