Reputation: 333
Here is my code;
var data = [[40, 20, 60], [20, 30, 10], [50, 75, 40]];
var averageData = [];
data.forEach(function(entries) {
entries.reduce(function(a, b) {
return a + b[1];
}, 0);
console.log(entries);
});
I would like to be able to add the numbers from each array together.
But I'm not sure how I can get each array of numbers added together from the forEach
loop?
From this data I would like to output instead [120, 60, 165]
.
It is important that the data is within a nested array, the aim is to try get it out of the nested array onto a single line with the above output.
Hope someone can offer some advice!
Thanks
Upvotes: 0
Views: 229
Reputation: 36609
Use Array#map
instead
Note that b[1]
holds nothing(undefined
) and entries.reduce
returns a reduced
value, either return it of keep it in variable
var data = [
[40, 20, 60],
[20, 30, 10],
[50, 75, 40]
];
var averageData = data.map(function(entries) {
return entries.reduce(function(a, b) {
return a + b;
}, 0);
});
console.log(averageData)
Edit- As suggested in comments by @Tushar, ES6 version
var data = [
[40, 20, 60],
[20, 30, 10],
[50, 75, 40]
];
console.log(data.map(arr => arr.reduce((a, b) => a + b, 0)));
Upvotes: 11
Reputation: 26
If your values are safe (meaning you know where there come from) you could use eval to quickly sum the values.
var data = [[40, 20, 60], [20, 30, 10], [50, 75, 40]];
var totals = [];
data.forEach(function(a, i) {
totals.push(eval(a.join('+')));
});
console.log(totals);
Not the most efficient way but it works
Upvotes: 0
Reputation: 489
reduce()
will return the sum as you want at last. See as below.
var data = [[40, 20, 60], [20, 30, 10], [50, 75, 40]];
var averageData = []
data.forEach(function(entries) {
var sum = entries.reduce(function(a, b) {
return a + b;
}, 0)
console.log(sum)
})
Upvotes: 0