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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With