
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Matching Object Values in 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 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.
So, the resultant object should look like −
const output = {a: 6, b: 9, c: 6, d: 3};
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
{ a: 6, b: 9, c: 6, d: 3 }
Advertisements