

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 - 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 } ]
- Related Questions & Answers
- Sorting objects by numeric values - JavaScript
- Sum from array values with similar key in JavaScript
- Sum of array object property values in new array of objects in JavaScript
- Merge objects in array with similar key JavaScript
- Sum all similar elements in one array - JavaScript
- Fill missing numeric values in a JavaScript array
- Sum identical elements within one array in JavaScript
- Sorting an array of objects by property values - JavaScript
- Fetch specific values from array of objects in JavaScript?
- Add values of matching keys in array of objects - JavaScript
- Finding the sum of unique array values - JavaScript
- Sum values in MySQL from similar day records
- JavaScript - length of array objects
- Compare array of objects - JavaScript
- Update an array of strings nested within an array of objects in MongoDB
Advertisements