I have an array of arrays with objects that looks like this:
var data = [
[{'name':'John', 'value':2},
{'name':'Randy', 'value':4}
],
[{'name':'Sarah', 'value':10},
{'name':'Julie', 'value':10}
]
];
I want to iterate through each array and add up values and store the totals in an array. What I came up with looks like this:
function add(accumulator, a) {
return accumulator + a;
}
var totals = [];
var yExtent = data.forEach(function(item) {
item.forEach(function(jtem) {
var subTotals = [];
subTotals.push(jtem.value);
return subTotals;
})
var localTotal = subTotals.reduce(add,0);
totals.push(localTotal);
return totals;
});
console.log(totals)
However, this results in the error: "subTotals is not defined"
Question
Is this happening because subTotals is not in the same scope as the other part of the function? If so, how should I proceed? I cannot put var localTotal = subTotals.reduce(add,0); in scope because the forEach() would calculate it too frequently and give me the wrong values. How should I modify this code to return my inner forEach() calculations to the outer?
undefined,forEachdoesn't return anything. Besides that, you have the scope issue of that variable.var subTotals = [];one line up out of the innerforEachreturn total(which is doing nothing anyway).map+reduce.