I have this multidimensional array and I need to merge the fields that are equal and sum the sum values
var data = [
[
{field: 123, sum: 100},
{field: 345, sum: 98}
],[
{field: 123, sum: 12},
{field: 345, sum: 20}
]
];
So from this array I need a new one like this.
var newArray = [
{field: 123, sum: 112},
{field: 345, sum: 118}
];
and here is my code.
var newArray = [];
for(var i = 0; i < data.length; i++) {
for(var j = 0; j < data[i].length; j++) {
var matched = false;
for(var c = 0; c < newArray.length; c++) {
if(data[i][j].field == newArray[c].field) {
matched = true;
newArray[c].sum + data[i][j].sum;
}
}
console.log(data[i][j]);
if(!matched) {
newArray.push(data[i][j]);
}
}
}
but I don't get the values right. console.log(newArray);