How to Group Array of Objects by Key in JavaScript
To group an array of objects by a key in JavaScript, use the
Array.prototype.reduce method to iterate over the array and collect objects into groups based on the key's value. This creates an object where each key is a group name and its value is an array of objects belonging to that group.Syntax
The common syntax to group objects by a key uses reduce:
array.reduce((accumulator, currentObject) => { ... }, initialValue): Iterates over each object.accumulator: The object collecting groups.currentObject[key]: The value used to group objects.initialValue: Usually an empty object{}to start grouping.
javascript
const grouped = array.reduce((acc, obj) => { const key = obj.groupKey; if (!acc[key]) { acc[key] = []; } acc[key].push(obj); return acc; }, {});
Example
This example groups an array of people by their age:
javascript
const people = [ { name: 'Alice', age: 21 }, { name: 'Bob', age: 25 }, { name: 'Charlie', age: 21 }, { name: 'David', age: 25 }, { name: 'Eve', age: 30 } ]; const groupedByAge = people.reduce((groups, person) => { const age = person.age; if (!groups[age]) { groups[age] = []; } groups[age].push(person); return groups; }, {}); console.log(groupedByAge);
Output
{"21":[{"name":"Alice","age":21},{"name":"Charlie","age":21}],"25":[{"name":"Bob","age":25},{"name":"David","age":25}],"30":[{"name":"Eve","age":30}]}
Common Pitfalls
Common mistakes when grouping by key include:
- Not initializing the group array before pushing objects, causing errors.
- Using the wrong key name or forgetting to access the key value.
- Mutating the original array instead of creating a new grouped object.
Always check if the group exists before pushing.
javascript
/* Wrong way: Missing initialization */ const wrongGroup = people.reduce((acc, person) => { acc[person.age].push(person); // Error: acc[person.age] may be undefined return acc; }, {}); /* Right way: Initialize if missing */ const rightGroup = people.reduce((acc, person) => { if (!acc[person.age]) { acc[person.age] = []; } acc[person.age].push(person); return acc; }, {});
Quick Reference
Tips for grouping arrays by key:
- Use
reduceto accumulate groups. - Check if the group key exists before adding.
- Return the accumulator each iteration.
- Use bracket notation
acc[key]for dynamic keys.
Key Takeaways
Use Array.prototype.reduce to group objects by a key into an object.
Always initialize the group array before pushing objects to avoid errors.
Access the grouping key dynamically using bracket notation.
Return the accumulator object in each reduce iteration.
Grouping creates a new object; it does not modify the original array.