Consider an array that contains objects. Each object of the array is composed of both label
and value
attributes. I want to be able to compare each object of the array, and if the labels are the same, sum their values so as the labels do not repeat and have the sum of all previous values.
Like, for instance, if the array was this:
[{
label: "A",
value: 10
}, {
label: "B",
value: 20
}, {
label: "C",
value: 30
}, {
label: "C",
value: 40
}, {
label: "D",
value: 12
}, {
label: "D",
value: 23
}]
In the end I would have the array with only four labels (A, B, C, D) and the value 10 for A, 20 for B, 70 for C and 35 for D.
I tried using a for loop:
for (i = 1; i < transformation.length; i++) {
if (transformation[i-1].label == transformation[i].label) {
result.label.push = transformation[i].label;
result.value.push = transformation[i-1].value + transformation[i].value;
}
};
But I got stuck here and have no ideas on how to deal with non repeated values. I need the final array to still be an array, not an object.