Weird Loop Using Recursion In Js Function
I am trying to sum the elements inside a nested array. For example arraySum([1,[2,3],5,[[4]]]) should return 15 Everything seems ok except when I try to return array.pop() + arrayS
Solution 1:
Some hearty recursion solves our problem here. The issue was that you were mutating the array while iterating over it, specifically pushing items back into it. In practice you should never do this.
functionarraySum(array) {
if (array.length === 0) {
return0;
}
return array.reduce((previous, current) => {
if (Array.isArray(current)) {
return previous + arraySum(current);
}
return previous + current;
}, 0);
}
console.log(arraySum([1, [2, 3], 5, [[4]]]));
Post a Comment for "Weird Loop Using Recursion In Js Function"