简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM