0

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

3 Answers 3

11

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)));

Sign up to request clarification or add additional context in comments.

1 Comment

ES6: data.map(arr => arr.reduce((a, b) => a + b, 0))
0

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)

})

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.