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!