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)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay