Array nested sum - recursion
Thu Jun 03 2021 04:24:43 GMT+0000 (Coordinated Universal Time)
Saved by
@ejiwen
// 3. Sum all numbers in an array containing nested arrays.
// arraySum([1,[2,3],[[4]],5]); // 15
var arraySum = function(array) {
var result = 0;
if(! Array.isArray(array)) {
return array;
} else {
array.forEach(arr => {
result += arraySum(arr);
})
}
return result;
};
console.log(arraySum([1,[2,3],[[4]],5]));
content_copyCOPY
Comments