I have an array of objects with number values that I am trying to loop over to get a result of and ARRAY of ARRAYS. Ive found examples of using for loop where the output is an ARRAY of OBJECTS. But I am having trouble looping over and adding the number values to create an array for each month value with the second value being a total of all the values listed for that month.
var input = [
{month: "Jan", value: 3},
{month: "Jan", value: 3.5},
{month: "Feb", value: 2.1},
{month: "Mar", value: 6},
{month: "Apr", value: 4.3},
{month: "May", value: 5.5},
{month: "Jun", value: 7},
{month: "Jun", value: 9},
{month: "Jul", value: 7},
{month: "Jul", value: 9},
{month: "Jul", value: 7},
{month: "Aug", value: 9},
{month: "Sep", value: 9},
{month: "Sep", value: 9},
{month: "Oct", value: 8},
{month: "Oct", value: 5},
{month: "Oct", value: 3},
{month: "Nov", value: 12},
{month: "Nov", value: 19.5},
];
var result = [];
for (var i = 0; i < input.length; i++) {
var data = input[i];
var found = false;
console.log(result[1][1], "help");
for (var j = 0; j < result.length; j++) {
if (result[j].month === data.month) {
found = true;
result[j][1] += data.value;
break;
}
}
if (!found) {
result.push([data.month, data.value]);
}
}
Currently returns an array of arrays but it is not adding the values instead it is making an array for each object.
My expected output would be:
[["Jan", 6.5],["Feb", 2.1],["Mar", 6],["Jun", 16]...etc]