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
Add matching object values in JavaScript
In JavaScript, you can add matching object values by iterating through an array of objects and accumulating values for common keys. This is useful for aggregating data from multiple objects.
Consider an array of objects like this:
const arr = [{a: 2, b: 5, c: 6}, {a: 3, b: 4, d: 1}, {a: 1, d: 2}];
console.log("Input array:", arr);
Input array: [ { a: 2, b: 5, c: 6 }, { a: 3, b: 4, d: 1 }, { a: 1, d: 2 } ]
Each object has unique properties within itself, but different objects can share common keys. We need to create a function that returns an object with all unique keys and their cumulative sum as values.
The expected output should be:
{ a: 6, b: 9, c: 6, d: 3 }
Using for Loop with Object.keys()
This method iterates through each object and uses Object.keys() to access all properties:
const arr = [{a: 2, b: 5, c: 6}, {a: 3, b: 4, d: 1}, {a: 1, d: 2}];
const sumArray = arr => {
const res = {};
for(let i = 0; i {
res[key] = (res[key] || 0) + arr[i][key];
});
}
return res;
};
console.log(sumArray(arr));
{ a: 6, b: 9, c: 6, d: 3 }
Using for...of Loop
A cleaner approach using for...of loop:
const arr = [{a: 2, b: 5, c: 6}, {a: 3, b: 4, d: 1}, {a: 1, d: 2}];
const sumArrayForOf = arr => {
const result = {};
for(const obj of arr) {
for(const key in obj) {
result[key] = (result[key] || 0) + obj[key];
}
}
return result;
};
console.log(sumArrayForOf(arr));
{ a: 6, b: 9, c: 6, d: 3 }
Using Array.reduce()
The most functional approach using reduce():
const arr = [{a: 2, b: 5, c: 6}, {a: 3, b: 4, d: 1}, {a: 1, d: 2}];
const sumArrayReduce = arr => {
return arr.reduce((acc, obj) => {
Object.keys(obj).forEach(key => {
acc[key] = (acc[key] || 0) + obj[key];
});
return acc;
}, {});
};
console.log(sumArrayReduce(arr));
{ a: 6, b: 9, c: 6, d: 3 }
How It Works
All methods follow the same logic:
- Initialize an empty result object
- Iterate through each object in the array
- For each key in the current object, add its value to the result
- Use
(res[key] || 0)to handle undefined keys (default to 0)
Comparison
| Method | Readability | Performance | Functional Style |
|---|---|---|---|
| for loop + Object.keys() | Good | Fast | No |
| for...of + for...in | Very Good | Fast | No |
| Array.reduce() | Good | Slightly slower | Yes |
Conclusion
Adding matching object values is accomplished by iterating through objects and accumulating values for common keys. The for...of approach offers the best balance of readability and performance for most use cases.
