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.
Approach to Find the Sum of All Elements in an ArrayInitialize a variable sum to store the total sum of all elements of the array. Traverse the array and add each element of the array with the sum variable. Finally, return the sum variable.
Let's see how to find the sum of the 2D array using the map function. Initialize the 2D array using lists. Pass the function sum and 2D array to the map function. Find the sum of resultant map object and print it.
The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With