sum of an array using recursion Javascript
function sumNumbersRecursively(input){
if (input.length == 0){
return 0;
} else{
return input.shift() + sumNumbersRecursively(input);
}
}
console.log(sumNumbersRecursively([2,3,4]))
A one-liner that meets all your requirements:
var sum = function(array) {
return (array.length === 0) ? 0 : array[0] + sum(array.slice(1));
}
// or in ES6
var sum = (array) => (array.length === 0) ? 0 : array[0] + sum(array.slice(1));
// Test cases
sum([1,2,3]); // 6
var s = [1,2,3];
sum(s); // 6
sum(s); // 6
Reasoning
- In a recursive call, you need to model your task as reduction to a base case. The simplest base case in this case is the empty array - at that point, your function should return zero.
- What should the reduction step be? Well you can model a sum of an array as the result of adding the first element to the
sum
of the remainder of the array - at some point, these successive calls will eventually result in a call tosum([])
, the answer to which you already know. That is exactly what the code above does. array.slice(1)
creates a shallow copy of the array starting from the first element onwards, and no mutation ever occurs on the original array. For conciseness, I have used a ternary expression.
Breakdown:
sum([1,2,3])
-> 1 + sum([2,3])
-> 1 + 2 + sum([3])
-> 1 + 2 + 3 + sum([])
-> 1 + 2 + 3 + 0
-> 6
You're on the right track, but consider that sum could take an optional second argument (that defaults to zero) that indicates the position to start summing from...
function sum(array, n) {
n ||= 0;
if (n === array.length) {
return 0;
} else {
return array[n] + sum(array, n + 1);
}
}