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 }
]

Updated on: 18-Sep-2020

637 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements