user1774309 user1774309 - 6 months ago 16
Javascript Question

JS How to make a reduce to sum a index of a array?

I need help to learn how to make a reduce to a array like this:

a=[ ["ww","fsf",40],["ww","fsf",30],["ww","fsf",10]]


I want to learn how to sum the 40+30+10 using the method reduce. I know how to do it if the array was [40,30,10].
Can anyone help me? Thank you.

Answer

.reduce applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value:

a.reduce(callback[, initialValue])

Your values will be arrays:

["ww","fsf",40]
["ww","fsf",30]
["ww","fsf",10]

So you can use:

a.reduce(function(sum, value) {
  return sum + value[2];
}, 0);

Or using ES6 new arrow functions:

 a.reduce((sum, value) => sum + value[2], 0);