0

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

corn
  • 9
  • 1
    this arises in this case because `acc` is always a reference to the same object, which is mutated by the reducer function in this case, and due to performance optimisations, the console isn't actually showing you the object at the time it was logged, but how it is later (when the `reduce` method has completed). Try logging `JSON.stringify(acc)` (or `JSON.parse(JSON.stringify(acc))` if you want to see it as an actual object) to see the "intermediate values". – Robin Zigmond Mar 01 '22 at 22:08
  • 1
    This is just how `console` works: it is lazy. When you click to see the contents of `acc`, then the contents are retrieved at that moment. It does not reflect the actual state at the moment of logging. – trincot Mar 01 '22 at 22:08
  • This makes much more sense. I logged `JSON.stringify(acc)` which showed the intermediate values. Thank you! – corn Mar 01 '22 at 22:21

0 Answers0