[Recursion] Build a function that sums AUTOMATICALLY ALL THE ELEMENTS in an array

Hey guys, thx for stopping by my question.
While studying [Replace Loops using Recursion] on the FCC tutorial,

An idea came up that I want to build a function using recursion that SUMS ALL THE ELEMENTS AUTOMATICALLY in an array.

So I tried with this one.

let multiArr = [1,2,3,4,5];
let n = multiArr.length;
console.log(n);// 5

function multiply(arr, n){
  if( n <= 0 ){
    return 1;
  } else {
    return arr[ n - 1 ] * multiply(arr, n - 1);
  }
}
console.log(multiply(multiArr, n)) // 120

let newArr = [1,2,3,4,5,6];
let n2 = newArr.length; // 6
console.log(multiply( newArr, n2)); //720 

But As you can see, you have to set ‘n’ for each array which is kind of annoying …

So, how can I build a function using recursion that sums all the elements in an array without taking care of ‘n’?!..

Thanks in advance!! :slight_smile:

N is just an array length.
You can check it inside of a recursive function, multiply what you want and call function again if array is longer than one (or whatever you want).

Thx for your reply. I knew ‘n’ was an array.length. But I’ve implemented it in a wrong way.

I should have invoked the function like below.

let newArr = [1,2,3,4,5,6];
console.log(multiply( newArr, newArr.length)); //720 

But when I first created the function, I put ’arr.length’ like below :slight_smile:


function multiply(arr,  arr.length){
  if( n <= 0 ){
    return 1;
  } else {
    return arr[ n - 1 ] * multiply(arr, n - 1);
  }
}

Thx your reply.

you can use default parameters, since we declare n after arr it can be set to whatever things arr has, so no need to even pass the length of the array:

const multiply = (arr, n = arr.length - 1) => 
n === 0 ? arr[0] : arr[n] * multiply(arr, n-1);

console.log(multiply([1, 2, 3, 4])); //24

or if you don’t like arrow functions

function multi(arr, n = arr.length - 1) {
  if(n === 0) return arr[0];
  else return arr[n] * multi(arr, n-1);
}
console.log(multi([1, 2, 3, 4])); //24
2 Likes

Thx for your detail reply!! :slight_smile:
It helped a lot !!!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.