Recursion version using Array.prototype.reduce
let arrayNumbers = [5, 7, [4, [2], 8, [1, 3], 2], [9, []], 1, 8];
function treeSum(array) {
return array.reduce(
(sum, n) =>
sum +
(typeof n === "number"
? // n is a number
n
: // n is an array
treeSum(n)),
0
);
}
console.log(treeSum(arrayNumbers) === 50);
Recursion version using for...of
let arrayNumbers = [5, 7, [4, [2], 8, [1, 3], 2], [9, []], 1, 8];
function treeSum(array, sum = 0) {
for (const n of array) {
sum += typeof n === "number" ? n : treeSum(n);
}
return sum;
}
console.log(treeSum(arrayNumbers) === 50);
Iteration version
let arrayNumbers = [5, 7, [4, [2], 8, [1, 3], 2], [9, []], 1, 8];
function treeSum(array) {
let sum = 0;
do {
// not summed values
let values = [];
for (const n of array) {
if (typeof n === "number") sum += n;
else values = values.concat(n);
}
array = values;
} while (array.length > 0);
return sum;
}
console.log(treeSum(arrayNumbers) === 50);
Oneline solution using Array.prototype.flat
let arrayNumbers = [5, 7, [4, [2], 8, [1, 3], 2], [9, []], 1, 8];
function treeSum(array) {
return array.flat(Infinity).reduce((sum, n) => sum + n, 0);
}
console.log(treeSum(arrayNumbers) === 50);
5?arrayNumbers.flat(Infinity).reduce((a, b) => a + b, 0)?Array.isArray? It's supported all the way down to IE9.Array.isArraycannot be used, then what else cannot be used either?flat,flatMap,reduce, recursion,typeof,instanceof,constructor, ...? Such requirements make no sense without more context.