Group by in JavaScript

Ramkumar Khubchandani
1 min readFeb 25, 2024

--

Grouping data by a specific characteristic is a common task in JavaScript. Here’s a breakdown using both built-in methods and custom functions:

1. Group by with Object.groupBy() (modern browsers):

This method is available in modern browsers and simplifies grouping:

const people = [
{ name: "Alice", age: 25, city: "New York" },
{ name: "Bob", age: 30, city: "London" },
// ... more people
];

const groupedByCity = people.groupBy(person => person.city);

console.log(groupedByCity);
// Output: {
// "New York": [{ name: "Alice", ... }, { name: "David", ... }],
// "London": [{ name: "Bob", ... }],
// // ... other cities
// }

2. Group by with reduce():

For more flexibility, use reduce():

const groupedByCity = people.reduce((groups, person) => {
const city = person.city;
groups[city] = groups[city] || [];
groups[city].push(person);
return groups;
}, {});

console.log(groupedByCity);
// Same output as above

3. Custom Group by Function:

For more control, create your own:

function groupBy(arr, keyFn) {
const groups = {};
arr.forEach(item => {
const key = keyFn(item);
groups[key] = groups[key] || [];
groups[key].push(item);
});
return groups;
}

const groupedByAge = groupBy(people, person => person.age);

console.log(groupedByAge);
// Output: {
// "25": [{ name: "Alice", ... }],
// // ... other ages
// }

Above are the easiest way to do group by in Javascript, I feel first one is the best one.

Want to learn more about such things ?

Follow me or message me on Linkedin.

--

--

Ramkumar Khubchandani
Ramkumar Khubchandani

Written by Ramkumar Khubchandani

Frontend Developer|Technical Content Writer|React|Angular|React-Native|Corporate Trainer|JavaScript|Trainer|Teacher| Mobile: 7709330265|ramkumarkhub@gmail.com

No responses yet