Created
July 26, 2019 22:02
-
-
Save sockbot/c14f10e955e59a0534053a4c8a373978 to your computer and use it in GitHub Desktop.
sum-all-numbers-in-array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sumItems(array) { | |
// console.log(typeof 1) | |
// let isAllNumbers = array.every(x => (typeof x === 'number')); | |
// console.log(isAllNumbers); | |
let sum = 0; | |
array.forEach(function(x){ | |
if (typeof x === 'number') { | |
sum += x; | |
} else { | |
sum += sumItems(x); | |
} | |
}); | |
// if (isAllNumbers === true) { | |
// return array.reduce((a, b) => a + b); | |
// } | |
return sum; | |
}; | |
let arr1 = [1, 2, 3, [4,3], 5]; | |
let arr2 = [[1, 2, [[3], 4]], 5, []]; | |
let arr3 = [[[[[[[[[[[[[1]]]]]]]]]]]]]; | |
console.log(sumItems(arr1)); | |
console.log(sumItems(arr2)); | |
console.log(sumItems(arr3)); | |
module.exports = sumItems; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment