
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
Sum Similar Numeric Values Within Array of Objects in JavaScript
Suppose, we have an array of objects like this −
const arr = [ {"firstName":"John", "value": 89}, {"firstName":"Peter", "value": 151}, {"firstName":"Anna", "value": 200}, {"firstName":"Peter", "value": 22}, {"firstName":"Anna","value": 60} ];
We are required to write a JavaScript function that takes in one such array and combines the value property of all those objects that have similar value for the firstName property.
Therefore, for the above array, the output should look like −
const output = [ {"firstName":"John", "value": 89}, {"firstName":"Peter", "value": 173}, {"firstName":"Anna", "value": 260} ];
For each object, we will recursively find their similar objects
(Similar objects for the context of this question are those that have the similar firstName value).
We will then add the value property to one object and delete the other object from the array. This will be done until we reach the end of the array. On reaching, we would have reduced our array to the desired array.
Example
Following is the code −
const arr = [ {"firstName":"John", "value": 89}, {"firstName":"Peter", "value": 151}, {"firstName":"Anna", "value": 200}, {"firstName":"Peter", "value": 22}, {"firstName":"Anna","value": 60} ]; const sumSimilar = arr => { const res = []; for(let i = 0; i < arr.length; i++){ const ind = res.findIndex(el => el.firstName === arr[i].firstName); if(ind === -1){ res.push(arr[i]); }else{ res[ind].value += arr[i].value; }; }; return res; }; console.log(sumSimilar(arr));
Output
This will produce the following output in console −
[ { firstName: 'John', value: 89 }, { firstName: 'Peter', value: 173 }, { firstName: 'Anna', value: 260 } ]
Advertisements