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
JavaScript: compare array element properties, and if identical, combine
When working with arrays of objects, you often need to combine objects that have identical properties. In this example, we'll consolidate storage devices with the same size by adding up their counts.
Suppose we have an array of objects containing information about data storage devices:
const drives = [
{size:"900GB", count:3},
{size:"900GB", count:100},
{size:"1200GB", count:5},
{size:"900GB", count:1}
];
console.log("Original array:", drives);
Original array: [
{ size: '900GB', count: 3 },
{ size: '900GB', count: 100 },
{ size: '1200GB', count: 5 },
{ size: '900GB', count: 1 }
]
Notice how the same size appears multiple times. We need to consolidate all repeated sizes into single entries while adding up their counts.
Using reduce() Method
The most efficient approach uses reduce() to build a map, then converts it back to an array:
const drives = [
{size:"900GB", count:3},
{size:"900GB", count:100},
{size:"1200GB", count:5},
{size:"900GB", count:1}
];
const groupDrives = (arr = []) => {
const map = arr.reduce((map, e) => {
if (e.size in map) {
map[e.size].count += e.count;
} else {
map[e.size] = { ...e }; // Create copy to avoid mutations
}
return map;
}, {});
return Object.values(map);
};
console.log(groupDrives(drives));
[ { size: '900GB', count: 104 }, { size: '1200GB', count: 5 } ]
Alternative: Using Map Object
For better performance with large datasets, you can use a Map object:
const drives = [
{size:"900GB", count:3},
{size:"900GB", count:100},
{size:"1200GB", count:5},
{size:"900GB", count:1}
];
const groupWithMap = (arr) => {
const map = new Map();
arr.forEach(item => {
if (map.has(item.size)) {
map.get(item.size).count += item.count;
} else {
map.set(item.size, { ...item });
}
});
return Array.from(map.values());
};
console.log(groupWithMap(drives));
[ { size: '900GB', count: 104 }, { size: '1200GB', count: 5 } ]
How It Works
Both methods follow the same logic:
- Create a map/object to store unique sizes as keys
- For each drive, check if its size already exists in the map
- If it exists, add the count to the existing entry
- If it doesn't exist, create a new entry
- Convert the map back to an array
Comparison
| Method | Performance | Memory Usage | Code Complexity |
|---|---|---|---|
| reduce() with Object | Good | Low | Medium |
| Map Object | Better | Slightly higher | Low |
Conclusion
Use reduce() for simple grouping tasks, or Map for better performance with large datasets. Both methods efficiently consolidate duplicate entries while preserving the original data structure.
