I have a nested array
[1,2,4,[2,6,[3,2],4],7]
Now the output array should be [1,2,4,4,12,9,6,8,7]
where each element is the output of element * depth of array
;
and now getting the sum of elements of array would give 53
I have implemented a recursive method as below
let level = 1
let sum = 0
function recursive(arr){
arr.forEach(i=> {
multiplier(i)
})
}
function multiplier(i){
if(Array.isArray(i)){
level++
recursive(i);
} else {
sum += i*level
}
}
What am i doing wrong here? How can I control the variable level ?
4
Answers
The issue lies in using the global variable
level
to track the depth of the nested array, which may lead to interference with other calls. You should pass the currentlevel
as a parameter to the recursive function and utilize that value to calculate the multiplier, ensuring that each recursive call maintains its ownlevel
and avoiding unintended side effects.Demo:
You’re not decrementing the level variable when you exit from a nested array.
and also not resetting the level variable properly when you start processing a new array.
Now,
recursive
function takes an additional argumentlevel
which represents the current depth of the array. When you encounter a nested array, you passlevel + 1
to the recursive call. When you exit from a nested array, you don’t need to decrement level since it’s passed by value and not by reference.There’s no need to have two separate functions. Just write a single
recursiveSum
or whatever you want to name it, and walk through the input.This has the advantage that it doesn’t depend on global variables. It doesn’t mutate the input array either. It’s a pure function without side effects.
You copuld take a single function which gets the array and possible known depth and return the total.