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?