Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // declare function arraySum
- function arraySum(i) {
- // var curentVal will hold current value of i[j] member
- // at first value of sum is ZERO
- var sum = 0;
- // i will be an array, containing integers, strings and/or arrays like itself.
- // Sum all the integers you find, anywhere in the nest of arrays.
- for(var j = 0; j < i.length; j++) {
- // curentVal = i[j];
- // if curentVal of i[j] is Array
- if(i[j] instanceof Array) {
- sum += arraySum(i[j]);
- } else if (typeof i[j] === 'number') {
- sum += i[j];
- }
- }
- return sum;
- }
- console.log(arraySum([[1,2,false],'4','5'])); // 3
- console.log(arraySum([[1,2,3],4,5])); // 15
- console.log(arraySum([[[[[[[[[1]]]]]]]], 1])); // 2
Advertisement
Add Comment
Please, Sign In to add comment