skip to Main Content

I’m trying to recursively go through an array, collect all the values and sum them. Any attempts to do this result in a stack overflow. Tell me how to implement a function 1) using an additional variable 2) without using an additional variable.

 const numbers = [
    {
        number: [
            {
                number: 3,
            },
            {
                number: [
                    {
                        number: 5
                    }
                ]
            },
        ]
    },
    {
        number: 8
    }
]

function getSumOfNumbers(numbers) {
    if (Array.isArray(numbers)) {
        for (const child of numbers) {
            getSumOfNumbers(child);
        }
    }
    if (!Array.isArray(numbers) && typeof (numbers) == 'object') {
        for (const key in numbers) {
            getSumOfNumbers(numbers[key]);
        }
    }
    if (typeof (numbers) == 'number') {
        return numbers + getSumOfNumbers(numbers);
    }
}

getSumOfNumbers(numbers)

2

Answers


  1. Chosen as BEST ANSWER

    I was able to return the sum of all values.

    function getSumOfNumbers(numbers) {
        if (typeof (numbers) == 'number') {
            return numbers;
        } else {
            let sum = 0;
            if (Array.isArray(numbers)) {
                for (const child of numbers) {
                    sum += getSumOfNumbers(child);
                }
            }
            if (!Array.isArray(numbers) && typeof (numbers) == 'object') {
                for (const key in numbers) {
                    sum += getSumOfNumbers(numbers[key]);
                }
            }
            return sum;
        }
    }
    

    how to now implement the function without using an additional variable SUM?


  2. You mean just return the reduced values?

    const getSumOfNumbers = (numbers) => {
      if (typeof numbers === 'number') return numbers;
      else if (Array.isArray(numbers)) return numbers.reduce((acc, child) => acc + getSumOfNumbers(child), 0);
      else if (typeof numbers === 'object' && numbers !== null)  return Object.values(numbers).reduce((acc, value) => acc + getSumOfNumbers(value), 0);
      return 0;
    };
    
    console.log(getSumOfNumbers(numbers))
    <script>
      const numbers = [{
          number: [{
              number: 3,
            },
            {
              number: [{
                number: 5
              }]
            },
          ]
        },
        {
          number: 8
        }
      ]
    </script>

    Terser

    const getSumOfNumbers = (numbers) => typeof numbers === 'number' ? numbers :
      (Array.isArray(numbers) || (typeof numbers === 'object' && numbers !== null)) ?
      Object.values(numbers).reduce((acc, value) => acc + getSumOfNumbers(value), 0) : 0;
    
    
    console.log(getSumOfNumbers(numbers));
    <script>
    const numbers = [
      {
        number: [
          {
            number: 3,
          },
          {
            number: [
              {
                number: 5
              }
            ]
          },
        ]
      },
      {
        number: 8
      },
      5,  // Simple number
      [1, 2, [3, 4]],  // Nested list
      {"a": 1, "b": 2, "c": {"d": 3, "e": 4}},  // Nested object
      [1, [2, [3, [4, [5]]]]],  // Deeply nested list
      {"a": 1, "b": {"c": 2, "d": {"e": 3, "f": 4}}},  // Deeply nested object
      [],  // Empty list
      {},  // Empty object
      null  // Null value
    ];
    
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search