Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
7
rated 0 times [  14] [ 7]  / answers: 1 / hits: 20035  / 9 Years ago, thu, november 12, 2015, 12:00:00

Let's say I have this:



function arrSum(){
*code here*
}


How do I write the arrSum function such that it can sum all the integers within a multidimensional array (of variable depth).



I.e.



arrSum([2, 5, [4, 6], 5]) === 22;


I know there must be an answer to this somewhere but I really can't find it. If this is a duplicate please let me know.


More From » arrays

 Answers
5

Simply you can write a function like this with recursion





function arrSum(arr) {
var sum = 0;
// iterate array using forEach, better to use for loop since it have higher performance
arr.forEach(function(v) {
// checking array element is an array
if (typeof v == 'object')
// if array then getting sum it's element (recursion)
sum += arrSum(v);
else
// else adding the value with sum
sum += v
})
// returning the result
return sum;
}

console.log(arrSum([2, 5, [4, 6], 5]) === 22);





Using for loop





function arrSum(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
if (typeof arr[i] == 'object')
sum += arrSum(arr[i]);
else
sum += arr[i];
}
return sum;
}

console.log(arrSum([2, 5, [4, 6], 5]) === 22);




[#64426] Tuesday, November 10, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jadyngraysons

Total Points: 455
Total Questions: 109
Total Answers: 98

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
jadyngraysons questions
Thu, Apr 23, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
Tue, Dec 31, 19, 00:00, 4 Years ago
;