简体   繁体   中英

Compute sum of numerical values of an array of arrays in JavaScript

Having this input:

myArray = [[32.4, "bla", 1.44, 0.5, 65.8, "abc"],
           [654, "ert"]
           [9.4, "a", 1.44, "abc"]];

An array of arrays, I want to compute the sum of each sub-array and also ignoring the string values.

I know that for a single array of this type the sum could be computed as:

sum = myArray.filter(n => !isNaN(n)).reduce((m, n) => m + n);

but when I try to use the same method for a matrix the result is 0 .

Any suggestions?

You could try to convert the value to a number with an unary plus + or take zero for adding.

 var array = [[32.4, "bla", 1.44, 0.5, 65.8, "abc"], [654, "ert"], [9.4, "a", 1.44, "abc"]], result = array.map(a => a.reduce((s, v) => s + (+v || 0), 0)); console.log(result); 

You could use map method and inside filter to get array of numbers only and then reduce to get sum for each array.

 const myArray = [ [32.4, "bla", 1.44, 0.5, 65.8, "abc"], [654, "ert"], [9.4, "a", 1.44, "abc"] ]; const result = myArray.map(arr => { return arr .filter(Number) .reduce((r, e) => r + e) }) console.log(result) 

As you're now dealing with an array of arrays, you could apply that same code, but it will have to be within an outer reduce to loop through the outer array:

const sum = myArray.reduce(
    (s, arr) => s + arr.filter(n => !isNaN(n)).reduce((m, n) => m + n),
    0
);

Live Example:

 const myArray = [ [32.4, "bla", 1.44, 0.5, 65.8, "abc"], [654, "ert"], [9.4, "a", 1.44, "abc"] ]; const sum = myArray.reduce((s, arr) => s + arr.filter(n => !isNaN(n)).reduce((m, n) => m + n), 0); console.log(sum); 

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