Please explain the code and elaborate what is running behind the code.
I'm confused with if part if(! acc[key])
. does it mean if key not in acc and set key with value array and jump out of if statement and push the obj in acc key value?
In case if key is in acc skip if statement and use another memory acc[key]
and set key which is in acc and set value with obj.
Is my explanation correct?
var people = [{
name: 'Alice',
age: 21
},
{
name: 'Max',
age: 20
},
{
name: 'Jane',
age: 20
}
];
function groupBy(objectArray, property) {
return objectArray.reduce(function(acc, obj) {
var key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj)
return acc;
}, {});
}
var groupedPeople = groupBy(people, 'age')
console.log(JSON.stringify(groupedPeople))