How to Group JavaScript Objects by Property Using reduce and the New groupBy Method
This guide shows how to transform an array of employee objects into a grouped structure by age using both a custom reduce‑based groupBy function and the modern Array.prototype.groupBy method, including examples of conditional grouping.
Assume we have an array of employee objects, each with name and age properties.
const people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
];We want to group these objects by age so that the result looks like:
const groupedPeople = {
20: [
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
],
21: [
{ name: 'Alice', age: 21 }
]
};The typical way is to use Array.prototype.reduce(), which iterates over the array and accumulates a single result. Using it we can implement a reusable groupBy function:
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;
}, {});
}
const groupedPeople = groupBy(people, 'age');
// groupedPeople is:
// {
// 20: [{ name: 'Max', age: 20 }, { name: 'Jane', age: 20 }],
// 21: [{ name: 'Alice', age: 21 }]
// }Modern JavaScript also provides a built‑in Array.prototype.groupBy() method, which simplifies the code:
const groupedPeople = people.groupBy(({ age }) => age);
// groupedPeople is:
// {
// 20: [{ name: 'Max', age: 20 }, { name: 'Jane', age: 20 }],
// 21: [{ name: 'Alice', age: 21 }]
// }You can also pass a custom grouping function, for example to separate items into two buckets based on a condition:
const groupedPeople = people.groupBy(({ age }) => age <= 20 ? 'a' : 'b');
// groupedPeople is:
// {
// a: [{ name: 'Max', age: 20 }, { name: 'Jane', age: 20 }],
// b: [{ name: 'Alice', age: 21 }]
// }Use the appropriate method to classify arrays by any property.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
