- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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 }
Advertisements