My task is to sum elements of an array and add it to second parameter (number) using recursion. Return only gives me last value of sum. I would appreciate any feedback :)
const getArraySum = (numbersArray, initialValue) => {
// let sum = initialValue
// for (let i = 0; i < numbersArray.length; i ) {
// sum = numbersArray[i]
// } return sum
if (numbersArray.length === 0 ) {
return initialValue
} else {
let sum = 0
sum = numbersArray[numbersArray.length-1]
console.log (numbersArray)
numbersArray.pop()
console.log (sum)
getArraySum (numbersArray)
return sum initialValue
}
};
const result1 = getArraySum([4,7,10], 5)
console.log (result1)
CodePudding user response:
You're ignoring the return value of the recursive call to getArraySum
. Instead, you should add it to the returned value:
const getArraySum = (numbersArray, initialValue) => {
if (numbersArray.length === 0) {
return initialValue
}
return numbersArray.pop() getArraySum(numbersArray, initialValue);
};
const result = getArraySum([4,7,10], 5)
console.log (result)
Note that the initialValue should only be taken into consideration once, in the end condition where the array is empty.
CodePudding user response:
The idea is to split an array into head
(=the first element or null
for an empty array) and tail
(everything else). Then, establish that the sum is head sum(tail)
:
let sum = ([head = null, ...tail]) =>
head === null ? 0 : head sum(tail)
console.log(sum([1,2,3,4]))
Having an initial value is a silly requirement, but it goes the same way:
let sum = ([head = null, ...tail], init = 0) =>
init (head === null ? 0 : head sum(tail))
console.log(sum([1, 2, 3, 4], 100))
CodePudding user response:
You could take the single values a summing variable and return immediately if the array is empty.
Otherwise return the function call with a new shorter array and hte sum of sum
and the first element.
const
getSum = (numbers, sum = 0) => {
if (!numbers.length) return sum;
return getSum(numbers.slice(1), sum numbers[0]);
};
console.log (getSum([4, 7, 10], 5));