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.
If we have a multi-dimensional array with strings and integers and we have to get the sum of the numbers, then following @Pranav C Balan's solution we could add a check in the else loop to check only for digits as below -
This can be done with lodash
_.flattenDeep
and_.sum
:A more modern approach using
.reduce()
:Simply you can write a function like this with recursion
Using
for
loopI would build a function similar to what Pranav C Balan with the difference that i would check the
isObject()
before callingforEach()
,This way i get around problems posed by sending a single
numeric
parameter, orNull
values.