Nane
Nane

Reputation: 433

How to add multidimensional array values in javascript?

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)

Upvotes: 2

Views: 351

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386883

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

Upvotes: 5

Related Questions