0

I run into this interesting code challenge: "Create a function that takes an array and returns the sum of all items in the array."

My solution is:

function sumArray(arr) {
    var merged = [].concat.apply([], arr);
    var sum = 0;
    merged.forEach(function(item) {
        sum = sum + item;
    });
    return sum;
}

The problem is that the above solution fails for: sumArray([1, [2, [1]], 3]), 7 because the flattening method does not go deep enough. Concretely, in the above case, console.log(merged) is [1, 2, [1], 3];

What flattening method would go as deep as necessary?

Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252
  • 2
    take `array.flat(Infinity)`. see [`Array#flat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat). – Nina Scholz Aug 29 '20 at 17:16
  • 1
    The simplest techniques for this would definitely be recursive, perhaps something like `const sumArray = (ns) => ns .reduce ((t, n) => t + (Array.isArray(n) ? sumArray(n) : n), 0)` – Scott Sauyet Aug 29 '20 at 17:17

1 Answers1

1

Use Array#flat() with infinite depth , or actual depth if known.

function sumArray(arr) {  
   return arr.flat(Infinity).reduce((a,b) => a+b)
}

console.log(sumArray([1, [2, [1]], 3]))
charlietfl
  • 170,828
  • 13
  • 121
  • 150