i have reviewed the other posts on stack overflow, and as mentioned I am trying to find the sum of an array using recursion and if its all numbers i.e [2, 6, 11, 4, 13, 5] it works fine but if in the array there are letters i.e["a","b","c"] it adds a 0 to the end giving "abc0" taking off the 0 after the return returns abcundefined
instead of return 0 i tried return array, which works for the ["a","b","c"] version but in [2, 6, 11, 4, 13, 5] returns it concat rather than addition. thanks in advance for your time and help. =)
function calculateSumRecursion(array) {
console.log(array)
if(array.length === 0 ) return 0
return array[0] calculateSumRecursion(array.slice(1))
}
CodePudding user response:
If you think that, you can stop if there is one element.
function calculateSumRecursion(array) {
// just to improve the basic logic, there can be other cases which can be handled i.e. if the array is empty.
if ( array.length === 1 ) array[0]
return array[0] calculateSumRecursion( array.slice(1) )
}
CodePudding user response:
You could solve this by simply changing the stop condition to 1 element.
function calculateSumRecursion(array) {
if (array.length < 1) throw "Can't calculate a sum of empty array";
if (array.length === 1) return array[0]
return array[0] calculateSumRecursion(array.slice(1))
}
array = [1, 2, 3, 4, 5, 6]
console.log(calculateSumRecursion(array))
array = ["a", "b", "c", "d", "e"]
console.log(calculateSumRecursion(array))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>