0

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.

2 Answers 2

4

.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);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. That was very usefull.
You're missing the initial value in the arrow function example.
@torazaburo Thanks for notifying me :-)
2
a.reduce((sum, row) => sum + row[row.length - 1], 0)

1 Comment

Can you explain the => ? Can you write the same using the syntax function(){} inside the reduce? Thank you.

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.