Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum multidimensional array elements if they have an duplicate

I have an array like this:

array = [[3, 'name'],[4, 'lastname'],[2, 'name'],[4, 'lastname']]

I need to sum the values if they have equal second element:

array = [[5, 'name'],[8, 'lastname']]

I tried to sort array by alphabetic order, I know there won't be more than one duplicate, and then if item is equal to next one sum their values, else do nothing. Maybe the condition should be stringified, this is just to show what I tried...

for(var n=0; n<finish.length; n++) {
    if(finish[n][1] === finish[n+1][1]) {
      finish[n][0] += finish[n+1][0];
    } else {
      finish[n][0] = finish[n][0];
    }
  }

The loop returns this error: Cannot read property '1' of undefined

like image 608
merko Avatar asked Feb 23 '26 04:02

merko


1 Answers

You can use reduce to summarise the data into an object. Use Object.values to convert the object into array

let array = [[3, 'name'],[4, 'lastname'],[2, 'name'],[4, 'lastname']];

let result = Object.values(array.reduce((c, v) => {
  if (c[v[1]]) c[v[1]][0] += v[0];     //Add the first element if already exist
  else c[v[1]] = v;                    //Assign the value if does not exist
  return c;
}, {}));

console.log(result);
like image 78
Eddie Avatar answered Feb 25 '26 17:02

Eddie