当前位置: 动力学知识库 > 问答 > 编程问答 >

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; }
分享给朋友:
您可能感兴趣的文章:
随机阅读: