So I was going through the MDN docs on the .reduce method in JavaScript and I was having a hard time understanding what is going on with the accumulator (acc). I was expecting the accumulator to populate/group according to age as it looped through objectArray(below). I've attached a picture of the console output and you can see that the acc is already populated/grouped. Any help would be greatly appreciated.
MDN .reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
let people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
];
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
console.log('acc',acc) //line not in MDN docs
let key = obj[property]
if (!acc[key]) {
acc[key] = []
}
acc[key].push(obj)
return acc
}, {})
}
let groupedPeople = groupBy(people, 'age')
// groupedPeople is:
// {
// 20: [
// { name: 'Max', age: 20 },
// { name: 'Jane', age: 20 }
// ],
// 21: [{ name: 'Alice', age: 21 }]
// }
Console Output: screenshot