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
Merge JavaScript objects with the same key value and count them
Suppose we have an array of objects like this:
const arr = [{
"value": 10,
"id": "111",
"name": "BlackCat",
}, {
"value": 10,
"id": "111",
"name": "BlackCat",
}, {
"value": 15,
"id": "777",
"name": "WhiteCat",
}];
We are required to write a JavaScript function that takes in one such array. The function should then merge all those objects together that have the common value for "id" property and add a "count" field to track how many times each unique object appears.
Therefore, for the above array, the output should look like:
const output = [{
"value": 10,
"id": "111",
"name": "BlackCat",
"count": 2,
}, {
"value": 15,
"id": "777",
"name": "WhiteCat",
"count": 1,
}]
Using reduce() Method
The most efficient approach uses the reduce() method to iterate through the array and build a new array with merged objects:
const arr = [{
"value": 10,
"id": "111",
"name": "BlackCat",
}, {
"value": 10,
"id": "111",
"name": "BlackCat",
}, {
"value": 15,
"id": "777",
"name": "WhiteCat",
}];
const combinedItems = (arr = []) => {
const res = arr.reduce((acc, obj) => {
let found = false;
for (let i = 0; i < acc.length; i++) {
if (acc[i].id === obj.id) {
found = true;
acc[i].count++;
}
}
if (!found) {
obj.count = 1;
acc.push(obj);
}
return acc;
}, []);
return res;
}
console.log(combinedItems(arr));
[
{ value: 10, id: '111', name: 'BlackCat', count: 2 },
{ value: 15, id: '777', name: 'WhiteCat', count: 1 }
]
Using Map for Better Performance
For larger datasets, using a Map provides better performance by avoiding the inner loop:
const arr = [{
"value": 10,
"id": "111",
"name": "BlackCat",
}, {
"value": 10,
"id": "111",
"name": "BlackCat",
}, {
"value": 15,
"id": "777",
"name": "WhiteCat",
}];
const combinedItemsMap = (arr = []) => {
const map = new Map();
arr.forEach(obj => {
if (map.has(obj.id)) {
map.get(obj.id).count++;
} else {
map.set(obj.id, {...obj, count: 1});
}
});
return Array.from(map.values());
}
console.log(combinedItemsMap(arr));
[
{ value: 10, id: '111', name: 'BlackCat', count: 2 },
{ value: 15, id: '777', name: 'WhiteCat', count: 1 }
]
How It Works
Both methods work by:
-
Method 1: Using
reduce()to build an accumulator array, checking if an object with the same ID already exists -
Method 2: Using a
Mapto store unique objects by ID as keys, making lookups faster
The Map approach is more efficient for large datasets because it has O(1) lookup time instead of O(n) for the array search.
Conclusion
Both methods effectively merge objects with the same ID and count occurrences. Use the Map approach for better performance with larger datasets, or the reduce method for simpler scenarios.
