Reputation: 95
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))
Upvotes: 1
Views: 270
Reputation: 21505
The if (!acc[key]) {...}
is just checking whether you've already captured any data for that key in the accumulator. If there's nothing there yet, you put an empty array there with acc[key] = [];
, so you'll be able to push data onto it in the next step.
The bug in your code is that you're also including the push
in that if clause; this means you'll only get the first object for each value for the given key. Instead you want all the objects for each value for that key.
Here's a fix, with some comments in the code explaining what it's doing at each step:
var people = [{
name: 'Alice',
age: 21
},
{
name: 'Max',
age: 20
},
{
name: 'Jane',
age: 20
}
];
function groupBy(objectArray, property) {
return objectArray.reduce(function(acc, obj) {
// stepping through each object in the array:
var key = obj[property]; // "key" is the value of the given property
// for this object
if (!acc[key]) { // if the accumulator doesn't already have
// data for that key,
acc[key] = []; // put an empty array there, so we can add
// data to it
}
// this next line was moved out of the if clause above it, because
// you always want it to happen:
acc[key].push(obj) // push this object onto the accumulator
// at that key
return acc;
}, {});
}
var groupedPeople = groupBy(people, 'age')
console.log(JSON.stringify(groupedPeople))
Upvotes: 1