1

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?

2
  • "but when I try to use the same method for a matrix..." Show us your attempt. I mean, you surely didn't just use the same code, as the structure of the data is completely different. So...? Commented Feb 26, 2018 at 12:47
  • 1
    You'er missing a , at the end of the second line. (It's not a syntax error because it means the subsequent array will be treated as a property accessor. But it's incorrect. :-) ) Commented Feb 26, 2018 at 12:54

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.