Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Group by element in array JavaScript
Grouping array elements by a specific property is a common JavaScript task. This tutorial shows how to group an array of objects by their uuid property into separate sub-arrays.
Problem Statement
Given an array of objects with similar properties, we need to group them by a specific key and return an array of arrays.
const arr = [
{"name": "toto", "uuid": 1111},
{"name": "tata", "uuid": 2222},
{"name": "titi", "uuid": 1111}
];
console.log("Original array:", arr);
Original array: [
{ name: 'toto', uuid: 1111 },
{ name: 'tata', uuid: 2222 },
{ name: 'titi', uuid: 1111 }
]
Expected Output
We want to group objects with the same uuid into sub-arrays:
const expectedOutput = [
[
{"name": "toto", "uuid": 1111},
{"name": "titi", "uuid": 1111}
],
[
{"name": "tata", "uuid": 2222}
]
];
Solution Using forEach and Hash Map
const arr = [
{"name": "toto", "uuid": 1111},
{"name": "tata", "uuid": 2222},
{"name": "titi", "uuid": 1111}
];
const groupByElement = arr => {
const hash = Object.create(null);
const result = [];
arr.forEach(el => {
if (!hash[el.uuid]) {
hash[el.uuid] = [];
result.push(hash[el.uuid]);
}
hash[el.uuid].push(el);
});
return result;
};
console.log(groupByElement(arr));
[
[ { name: 'toto', uuid: 1111 }, { name: 'titi', uuid: 1111 } ],
[ { name: 'tata', uuid: 2222 } ]
]
Alternative Solution Using reduce()
const groupByProperty = (arr, property) => {
const grouped = arr.reduce((acc, item) => {
const key = item[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(item);
return acc;
}, {});
return Object.values(grouped);
};
const arr = [
{"name": "toto", "uuid": 1111},
{"name": "tata", "uuid": 2222},
{"name": "titi", "uuid": 1111}
];
console.log(groupByProperty(arr, 'uuid'));
[
[ { name: 'toto', uuid: 1111 }, { name: 'titi', uuid: 1111 } ],
[ { name: 'tata', uuid: 2222 } ]
]
How It Works
Both solutions use a hash map approach:
- Create an empty hash object to track groups
- Iterate through each array element
- Use the grouping property as the hash key
- If the key doesn't exist, create a new array for that group
- Add the current element to its corresponding group
- Return the grouped arrays
Comparison
| Method | Flexibility | Readability | Performance |
|---|---|---|---|
| forEach + Hash | Fixed property | Good | Fast |
| reduce() | Dynamic property | Better | Fast |
Conclusion
Both methods efficiently group array elements by a property. The reduce() approach offers more flexibility by accepting the property name as a parameter, making it reusable for different grouping scenarios.
Advertisements
