One way to solve this is by breaking the array into two parts, calculating the sum of each part, and then adding the results.
For example, the implementation below separates the array into its first element and all the remaining elements. If the first element is an array, sum
is recursively applied, otherwise the value is used directly. For the rest of the array, sum
is recursively applied.
const sum = function(array) {
if (array.length === 0) return 0;
let first = array[0];
if (Array.isArray(first))
first = sum(first);
const rest = sum(array.slice(1));
return first + rest;
}
const array = [ 5, 7, [ 4, [ 2 ], 8, [ 1, 3 ], 2 ], [ 9, [] ], 1, 8 ];
console.log(sum(array)); // 50