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
Nane
4836 gold badges40 silver badges85 bronze badges
1 Answer 1
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
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Pointy
In an arrow function with a single expression, there's an implicit
return.lang-js