Skip to content

Instantly share code, notes, and snippets.

@sockbot
Created July 26, 2019 22:02
Show Gist options
  • Save sockbot/c14f10e955e59a0534053a4c8a373978 to your computer and use it in GitHub Desktop.
Save sockbot/c14f10e955e59a0534053a4c8a373978 to your computer and use it in GitHub Desktop.
sum-all-numbers-in-array
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