Last modified: Aug 03, 2026
Group JavaScript Array Items by Key
Grouping array items is a common task. You often need to organize data by a specific property. This guide shows you clean ways to do it.
We will explore three main methods. First, the classic reduce() approach. Second, using a Map for better performance. Third, the modern Object.groupBy() method. All are useful in different situations.
Why Group Array Items?
Grouping helps you understand data better. Imagine you have a list of products. You want to see them by category. Or you have users and want to group them by their country. This transforms flat data into a structured object.
This is essential for dashboards, reports, and UI lists. It makes data easier to manage and display. Let's start with the most common technique using reduce().
Method 1: Using reduce()
The reduce() method is powerful. It iterates over the array and builds an accumulator. This accumulator becomes your grouped object. It's a classic pattern for grouping.
Here is a simple example. We have an array of people. We will group them by their city.
// Sample data
const people = [
{ name: 'Alice', city: 'New York' },
{ name: 'Bob', city: 'London' },
{ name: 'Charlie', city: 'New York' },
{ name: 'Diana', city: 'Paris' }
];
// Group by city using reduce()
const groupedByCity = people.reduce((result, person) => {
// Get the key (city name)
const key = person.city;
// If the key doesn't exist, create an empty array
if (!result[key]) {
result[key] = [];
}
// Push the current person into the correct group
result[key].push(person);
// Return the accumulator for the next iteration
return result;
}, {});
console.log(groupedByCity);
Let's see the output of this code.
{
'New York': [
{ name: 'Alice', city: 'New York' },
{ name: 'Charlie', city: 'New York' }
],
'London': [ { name: 'Bob', city: 'London' } ],
'Paris': [ { name: 'Diana', city: 'Paris' } ]
}
This works perfectly. The logic is clear. We check if the key exists. If not, we create it. Then we add the item. This is a solid foundation for grouping by key.
Method 2: Using Map for Better Performance
Using a Map is often better for large datasets. It preserves insertion order. It also avoids issues with prototype properties. This is a more robust approach.
Here is how you can use a Map to group items. It's similar to reduce, but we use a Map object.
// Sample data
const products = [
{ id: 1, type: 'fruit', name: 'Apple' },
{ id: 2, type: 'vegetable', name: 'Carrot' },
{ id: 3, type: 'fruit', name: 'Banana' }
];
// Group by type using Map
const groupedProducts = products.reduce((map, product) => {
const key = product.type;
// Check if the Map has this key
if (!map.has(key)) {
map.set(key, []);
}
// Get the array and push the product
map.get(key).push(product);
return map;
}, new Map());
console.log(groupedProducts);
Now, let's check the output. It looks different from a plain object.
Map(2) {
'fruit' => [ { id: 1, type: 'fruit', name: 'Apple' }, { id: 3, type: 'fruit', name: 'Banana' } ],
'vegetable' => [ { id: 2, type: 'vegetable', name: 'Carrot' } ]
}
You can easily convert this Map to an object if needed. Use Object.fromEntries(). This method is very efficient for grouping array items.
Method 3: Modern Object.groupBy()
JavaScript now has a native method for this. It's called Object.groupBy(). This is the simplest way to group items. It's clean and readable.
This method is available in modern browsers and Node.js. It takes a callback function. This function returns the key for each item.
// Sample data
const animals = [
{ name: 'Lion', category: 'mammal' },
{ name: 'Eagle', category: 'bird' },
{ name: 'Shark', category: 'fish' },
{ name: 'Tiger', category: 'mammal' }
];
// Group by category using Object.groupBy()
const groupedAnimals = Object.groupBy(animals, (animal) => {
return animal.category;
});
console.log(groupedAnimals);
Here is the output. It's very clean and direct.
{
mammal: [
{ name: 'Lion', category: 'mammal' },
{ name: 'Tiger', category: 'mammal' }
],
bird: [ { name: 'Eagle', category: 'bird' } ],
fish: [ { name: 'Shark', category: 'fish' } ]
}
Notice that the keys are not quoted. This is because they are valid identifiers. This method is the recommended way for new code. It's much easier to read than the manual reduce() approach.
Grouping by Nested Keys
Sometimes your key is not a direct property. It might be nested inside an object. You can still group by it. Just access the nested property in your callback.
Let's group by a nested property using Object.groupBy().
// Data with nested objects
const orders = [
{ id: 1, customer: { country: 'USA' } },
{ id: 2, customer: { country: 'UK' } },
{ id: 3, customer: { country: 'USA' } }
];
// Group by nested key
const groupedByCountry = Object.groupBy(orders, (order) => {
return order.customer.country;
});
console.log(groupedByCountry);
The output groups all orders from the same country together.
{
USA: [ { id: 1, customer: { country: 'USA' } }, { id: 3, customer: { country: 'USA' } } ],
UK: [ { id: 2, customer: { country: 'UK' } } ]
}
This shows the flexibility of grouping. You can use any expression to derive your key. This is a powerful way to organize complex data.
Practical Use Case: Grouping with Count
Grouping is often used with counting. You might want to know how many items are in each group. This is easy to do with the grouped result.
Here is an example. We will count the number of people in each city.
// Data
const attendees = [
{ name: 'John', city: 'Berlin' },
{ name: 'Jane', city: 'Berlin' },
{ name: 'Mike', city: 'Rome' }
];
// Group first
const grouped = Object.groupBy(attendees, (person) => person.city);
// Count each group
const counts = Object.keys(grouped).map(city => ({
city: city,
count: grouped[city].length
}));
console.log(counts);
This creates a new array with the counts.
[ { city: 'Berlin', count: 2 }, { city: 'Rome', count: 1 } ]
This pattern is very common. It turns raw data into useful statistics. You can easily extend this to calculate sums or averages.
Important Things to Remember
When grouping, always consider the data type of your key. If you group by a number, the key becomes a string. This is automatic in JavaScript objects. Be aware of this when you access the groups later.
Also, remember that Object.groupBy() is static. It does not modify the original array. It returns a new object. This is good for keeping your data immutable. For more array techniques, check out our guide on JavaScript Array Methods Guide.
If you are working with a lot of data, performance matters. The Map method is often faster. But for most cases, Object.groupBy() is perfectly fine. It's all about readability and maintainability.
Conclusion
Grouping array items by key is a fundamental skill. We learned three ways to do it. The reduce() method is the classic approach. The Map method is great for performance. The Object.groupBy() method is the modern and cleanest solution.
Start with Object.groupBy() for new projects. It makes your code shorter and easier to understand. If you need more control, use reduce(). For very large datasets, consider using a Map. This skill will help you in many real-world applications.
To deepen your understanding, explore how JavaScript Array reduce() Explained works in detail. You can also see how to structure data with our JavaScript Array of Objects Guide. Practice with different datasets to master this essential technique.