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 Working with Objects in Arrays

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree
karan Badhwar
Web Development Techdegree Student 15,454 Points

Help me understand this example. please

I saw an example for reduce (), but this is very confusing can somebody please explain me and is this a write way to write a syntax

const people = [
  {name: 'kyle', age: 26},
  {name: 'karan', age : 27},
  {name: 'Rahil', age : 27},
  {name: 'Vinay', age: 25}
];
const result = people.reduce(groupedPeople, person) => {
  const age = person.age;
  if (groupedPeople[age] == null) groupedPeople[age] = []
  groupedPeople[age].push(person)
}, {});

console.log(result);

1 Answer

Steven Parker
Steven Parker
217,627 Points

This syntax is fine, but it is perhaps a bit complex for a first example.

Take a look at the thorough explanation on the MDN page for reduce(). It also contains several more examples of different levels of complexity.

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree
karan Badhwar
Web Development Techdegree Student 15,454 Points

Steven Parker, but if ever I encounter such type of syntax how do I know for future reference what's happening, coz now it takes me time to understand that

Steven Parker
Steven Parker
217,627 Points

Reduce is perhaps one of the less intuitive things in JavaScript. Luckily, there are always handy online references. If I haven't it used much recently, I have to go look up the syntax myself.