Skip to content
Advertisement

How to get these 2D array elements summed if there are duplicates?

I have seen a couple of examples, but handling arrays with 2 elements in it and I was wondering what changes would have to be made so that this one gets summed by comparing the first element and calculating the 4th elements

array = 
[
   [2, 'name1','something',15],
   [3, 'name10','something',5],
   [5, 'name20','something',20],
   [2, 'name15','something',3]
]

Expected Result

array = 
[
   [2, 'name1','something',18],
   [3, 'name10','something',5],
   [5, 'name20','something',20]
]

Appreciate your help!

Thanks!

Advertisement

Answer

Just update the array indices of the required elements

In my test case, I changed the indices used in the script. The script used would be as follows:

function myFunction() {
  var array = [
    [2, 'name1', 'something', 15],
    [3, 'name10', 'something', 5],
    [5, 'name20', 'something', 20],
    [2, 'name15', 'something', 3]
  ]
  var result = Object.values(array.reduce((c, v) => {
    if (c[v[0]]) c[v[0]][3] += v[3]; // Updated the indices
    else c[v[0]] = v; // Updated the indices
    return c;
  }, {}));

  console.log(result);
}

From here, index [0] represents the elements in the first column (2,3,5,2) while index [3] represents the elements in the last column (15,5,20,3). So basically, the script only processed the first and last columns to achieve your desired output.

Output

Output

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement