Anyone can help me? i dont know where is my failure
Implement the
restArray
function: from an array in which each position can be a single number or another nested array of numbers, determine the sum of all numbers contained in the array.
The array will be received by parameter. Example:
const array = [3, [7, [5,6]], [9,6], 4];
restArray(array); --> It should return 40 and you subtract the result by the number of arrays, not counting the parent.
Example:
40-3 = 37
var restArray = function(array) {
let sum = 0;
if (array.length === 0) {
return -1;
}
for (arr of array) {
if (!Array.isArray(arr)) {
sum = arr;
} else {
sum = restArray(arr);
}
}
return sum;
};
console.log(restArray([3, [7, [5,6]], [9,6], 4]));
CodePudding user response:
Just a minor mistake in your code. As the top level array should not count for subtracting one from the sum, you should not have that case handled in the first if
block.
Instead apply that minus one when coming back from recursion, so to account for that nested array:
var restArray = function(array){
let sum = 0;
for (arr of array) {
if (!Array.isArray(arr)) {
sum = arr;
} else {
sum = restArray(arr) - 1;
}
}
return sum;
};
const array = [3, [7, [5,6]], [9,6], 4];
console.log(restArray(array));
It is possible to use reduce
to shorten the code a bit and use a bit more functional programming approach:
const restArray = array =>
array.reduce((sum, arr) =>
sum (Array.isArray(arr) ? restArray(arr) - 1 : arr)
, 0);
const array = [3, [7, [5,6]], [9,6], 4];
console.log(restArray(array));
CodePudding user response:
Here's a way to do it without recursion:
flatten the array of arrays down to a single array
array.flat(Infinity)
then add all of the numbers together with
.reduce()
.reduce((sum, cur) => sum cur)
const numbers = [3, [7, [5,6]], [9,6], 4];
console.log(numbers.flat(Infinity).reduce((sum, cur) => sum cur))