1

I've been looking through ways to count the number of occurrences of a specific value in an array of objects. I found this answer about using the reduce method on the array, as in their example:

const people = [
    {name: 'John', group: 'A'},
    {name: 'Andrew', group: 'C'},
    {name: 'Peter', group: 'A'},
    {name: 'James', group: 'B'},
    {name: 'Hanna', group: 'A'},
    {name: 'Adam', group: 'B'},
];
const groupInfo = people.reduce((groups, person) => {
    const {A = 0, B = 0, C = 0} = groups;
    //...rest of the code
}, {})

This code works for my case, however I still cannot fully grasp how the logic works, especially the destructuring of groups in const {A = 0, B = 0, C = 0} = groups;.

I am confused, as this shoud return a Cannot read property 'A' of undefined since the initial value for the groups is an empty object.

I am asking for someone to explain this further for future reference. Thank you!

Echo
  • 521
  • 5
  • 16
  • 1
    `{ A = 0, ... }` - this means that if `A` is undefined, assign the default value of zero to it and that is what's happening in the first iteration. Same applies to `B` and `C` – Yousaf Sep 29 '21 at 10:42
  • "*this shoud return a Cannot read property 'A' of undefined since the initial value for the groups is an empty object.*" an empty object is ***not*** `undefined`. try it `const obj = {}; const a = obj.a`. That's essentially the same as `const {a} = obj` – VLAZ Sep 29 '21 at 10:43
  • @VLAZ might have phrased that wrong. What I really meant was that when I comment out everything else except the destructuring part, I get an error of undefined. – Echo Sep 29 '21 at 10:47
  • 1
    "*when I comment out everything else except the destructuring part, I get an error of undefined.*" that is a completely different to what you said in your question. Yes, if you comment out everything, then *the function implicitly returns `undefined`* as there is no code that will return anything else. And that value becomes `groups` next iteration. So when `groups = undefined`, then there is a problem – VLAZ Sep 29 '21 at 10:50

0 Answers0