DEV Community

chandra penugonda
chandra penugonda

Posted on

Compute the sum of an array of integers using Recursion

Problem statement:

Compute the sum of an array of integers.
sum([1,2,3,4,5,6]); // 21

var sum = function(array) {
    // start here
};
Enter fullscreen mode Exit fullscreen mode

solution:

var sum = function (array) {
  if (array.length === 1) return array[0];
  return array[0] + sum(array.slice(1));
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)