1

I want to make a function that receives two arrays and returns a new array. The function needs to:

  1. compare two arrays of objects by a key('name')
  2. For elements with duplicate keys, add the values('grade').
  3. For elements with unique keys (no duplicates), just push the element as it is in the resulting array.

For example, with these two arrays arr1 and arr2

const arr1 = [{"name": "A", "grade": 50},{"name": "B","grade": 30},{"name": "C", "grade": 80}];
const arr2 = [{"name": "A", "grade": 70},{"name": "B","grade": 10}];

I want to return a new array such as:

const res = [{"name": "A", "grade": 120},{"name": "B","grade": 40},{"name": "C", "grade": 80}];

I tried nested loops with forEach and map but nothing seemed to work. I would very much appreciate your help. Thank you in advance!

Harsh Nagalla
  • 642
  • 1
  • 6
  • 17
sun0115
  • 11
  • 1
  • Hi, welcome to SO! Please post your code so far so that we can help you better. – georg May 04 '21 at 08:40
  • 1
    You can [merge](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) the two arrays and then group and sum by using one of the approaches outlined here: [Sum similar keys in an array of objects](https://stackoverflow.com/q/24444738) – Nick Parsons May 04 '21 at 08:41

1 Answers1

2

I recommend using reduce for that.

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

const arr1 = [{"name": "A", "grade": 50},{"name": "B","grade": 30},{"name": "C", grade: 80}];
const arr2 = [{"name": "A", "grade": 70},{"name": "B","grade": 10}];

const res = Object.values([...arr1, ...arr2].reduce((sum, { name, grade }) => {
  sum[name] = { name, grade: (sum[name] ? sum[name].grade : 0) + grade  };
  return sum;
}, {}));

console.log(res);
Ran Turner
  • 1,710
  • 1
  • 6
  • 10