2

I am pretty new to javascript.I am confused with javascript reduce. this is my array value

var result = [ 
 [ 0, 4, 22 ]//26,
 [ 0, 9, 19 ]//28 
 ]

I want to add this array value like this..

 [
 [26],
 [28]
 ]

And again I have to add this value like this..

26+28=54

this is my try this gives me undefined..

var sum = result.map((data) => {
 data.reduce(function (total ,curr) {
 return total+curr
 })
});
console.log(sum)
asked Oct 17, 2016 at 13:19

1 Answer 1

5

You need a return statement in block statements

var sum = result.map(data => {
 return data.reduce(function (total, curr) {
// ^^^^^^
 return total + curr;
 });
});

or without block statement

var sum = result.map(data => data.reduce((total, curr) => total + curr));

To answer the last part question, I suggest to create a function for adding values and use it as callback for Array#reduce.

var add = (a, b) => a + b,
 result = [[0, 4, 22], [0, 9, 19]],
 sum = result.map(a => a.reduce(add)),
 total = sum.reduce(add);
console.log(sum);
console.log(total);
.as-console-wrapper { max-height: 100% !important; top: 0; }

answered Oct 17, 2016 at 13:21
Sign up to request clarification or add additional context in comments.

1 Comment

In an arrow function with a single expression, there's an implicit return.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.