- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add values of matching keys in array of objects - JavaScript
Suppose we have an array of objects like this −
const arr = [{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}];
Each object is bound to have unique keys in itself (for it to be a valid object), but two different objects can have the common keys (for the purpose of this question)
We are required to write a JavaScript function that takes in one such array and returns an object with all the unique keys present in the array and their values cumulative sum as the value
Therefore, the resultant object should look like −
const output = {a: 6, b: 9, c: 6, d: 3};
Example
Following is the code −
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 < arr.length; i++){ Object.keys(arr[i]).forEach(key => { res[key] = (res[key] || 0) + arr[i][key]; }); }; return res; }; console.log(sumArray(arr));
Output
This will produce the following output in console −
{ a: 6, b: 9, c: 6, d: 3 }
- Related Articles
- Comparing objects in JavaScript and return array of common keys having common values
- Add matching object values in JavaScript
- Split keys and values into separate objects - JavaScript
- Fetch specific values from array of objects in JavaScript?
- Sum of array object property values in new array of objects in JavaScript
- Add property to common items in array and array of objects - JavaScript?
- Sorting an array of objects by property values - JavaScript
- Sum similar numeric values within array of objects - JavaScript
- Get only specific values in an array of objects in JavaScript?
- Maps in JavaScript takes keys and values array and maps the values to the corresponding keys
- Manipulating objects in array of objects in JavaScript
- Filtering array of objects in JavaScript
- Combine array of objects in JavaScript
- Array of objects to array of arrays in JavaScript
- Compare array of objects - JavaScript

Advertisements