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

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 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
229,744 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 seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 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
229,744 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.