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
I was able to return the sum of all values.
how to now implement the function without using an additional variable SUM?
You mean just return the reduced values?
Terser