DEV Community

Cover image for groupBy on an array of objects in javascript
Dezina
Dezina

Posted on

groupBy on an array of objects in javascript

const people = [
{ name: 'Lee', age: 21 },
{ name: 'Ajay', age: 20 },
{ name: 'Jane', age: 20 }
];
function groupBy(objectArray, property) {
return objectArray.reduce((acc, obj) => {
const key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
// Add object to list for given key's value
acc[key].push(obj);
return acc;
}, {});
}
const groupedPeople = groupBy(people, 'age');
console.log(groupedPeople);

Top comments (0)