skip to Main Content

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


  1. 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 current level as a parameter to the recursive function and utilize that value to calculate the multiplier, ensuring that each recursive call maintains its own level and avoiding unintended side effects.

    Demo:

    let sum = 0;
    
    function recursive(arr, level) {
      arr.forEach((i) => {
        multiplier(i, level);
      });
    }
    
    function multiplier(i, level) {
      if (Array.isArray(i)) {
        recursive(i, level + 1);
      } else {
        sum += i * level;
      }
    }
    
    const inputArray = [1, 2, 4, [2, 6, [3, 2], 4], 7];
    recursive(inputArray, 1);
    
    console.log(sum); //53
    Login or Signup to reply.
  2. 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.

    let sum = 0;
    
    function recursive(arr, level) {
        arr.forEach(i => {
            multiplier(i, level);
        });
    }
    
    function multiplier(i, level) {
        if (Array.isArray(i)) {
            recursive(i, level + 1);
        } else {
            sum += i * level;
        }
    }
    
    // Test
    let array = [1, 2, 4, [2, 6, [3, 2], 4], 7];
    recursive(array, 1);
    console.log(sum); // Output should be 53

    Now, recursive function takes an additional argument level which represents the current depth of the array. When you encounter a nested array, you pass level + 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.

    Login or Signup to reply.
  3. 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.

    function recursiveSum(arr, level=1) {
        let sum = 0;
        for (const el of arr) {
            if (Array.isArray(el)) {
                sum += recursiveSum(el, level + 1);
            } else {
                // You might want to check that `el` is actually
                // a number here, just to be safe.
                sum += el * level;
            }
        }
    
        return sum;
    }
    

    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.

    Login or Signup to reply.
  4. You copuld take a single function which gets the array and possible known depth and return the total.

    const
        data = [1, 2, 4, [2, 6, [3, 2], 4], 7],
        sum = (data, depth = 1) => {
            let total = 0;
            for (const value of data) {
                total += Array.isArray(value)
                    ? sum(value, depth + 1)
                    : value * depth;
            }
            return total;
        },
        result = sum(data);
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search