I'm not getting the logic written in if condition, I tried to console log the typeof acc, but it is undefined
let people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
];
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
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 }]
// }
CodePudding user response:
The reduce
is grouping by certain property. This involves creating arrays in the object keyed by each grouping and pushing the items into the array. If one particular item is the first member of its group encountered in the course of iterating, there will not yet be an array at the key to push to. Thus--
if (!acc[key]) {
acc[key] = []
}
-- checks to see if there is an array available yet at the key to push to. If not, then it will add an array at the key for group members to be added to. So, this if
condition will only evaluate as true
a single time for each group-- the very first time a member of the group is encountered.