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
Sum arrays repeated value - JavaScript
Suppose, we have an array of objects like this −
const arr = [
{'ID-01':1},
{'ID-02':3},
{'ID-01':3},
{'ID-02':5}
];
We are required to add the values for all these objects together that have identical keys
Therefore, for this array, the output should be −
const output = [{'ID-01':4}, {'ID-02':8}];
We will loop over the array, check for existing objects with the same keys, if they are there, we add value to it otherwise we push new objects to the array.
Using Array Prototype Extension
The first approach extends the Array prototype to find objects by key:
const arr = [
{'ID-01':1},
{'ID-02':3},
{'ID-01':3},
{'ID-02':5}
];
const indexOf = function(key){
return this.findIndex(el => typeof el[key] === 'number')
};
Array.prototype.indexOf = indexOf;
const groupArray = arr => {
const res = [];
for(let i = 0; i
[ { 'ID-01': 4 }, { 'ID-02': 8 } ]
Using reduce() Method
A more modern approach using the reduce() method:
const arr = [
{'ID-01':1},
{'ID-02':3},
{'ID-01':3},
{'ID-02':5}
];
const sumRepeatedValues = (arr) => {
const result = arr.reduce((acc, obj) => {
const key = Object.keys(obj)[0];
const value = obj[key];
const existing = acc.find(item => item.hasOwnProperty(key));
if (existing) {
existing[key] += value;
} else {
acc.push({[key]: value});
}
return acc;
}, []);
return result;
};
console.log(sumRepeatedValues(arr));
[ { 'ID-01': 4 }, { 'ID-02': 8 } ]
Using Map for Better Performance
For larger arrays, using a Map provides better performance:
const arr = [
{'ID-01':1},
{'ID-02':3},
{'ID-01':3},
{'ID-02':5}
];
const sumWithMap = (arr) => {
const map = new Map();
arr.forEach(obj => {
const key = Object.keys(obj)[0];
const value = obj[key];
if (map.has(key)) {
map.set(key, map.get(key) + value);
} else {
map.set(key, value);
}
});
return Array.from(map, ([key, value]) => ({[key]: value}));
};
console.log(sumWithMap(arr));
[ { 'ID-01': 4 }, { 'ID-02': 8 } ]
Comparison
| Method | Readability | Performance | Modern JS |
|---|---|---|---|
| Array Extension | Medium | Good | No |
| reduce() | High | Good | Yes |
| Map | High | Best | Yes |
Conclusion
Use the reduce() method for most cases as it's readable and functional. For performance-critical applications with large datasets, the Map approach is recommended.
Advertisements
