How to make a function that returns the factorial of each integer in an array JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are here required to write a JavaScript function that takes in an array of numbers and returns another array with the factorial of corresponding elements of the array. We will first write a recursive method that takes in a number and returns its factorial and then we will iterate over the array, calculating the factorial of each element of array and then finally we will return the new array of factorials.

Therefore, let’s write the code for this

Example

const arr = [4, 8, 2, 7, 6, 20, 11, 17, 12, 9];
const factorial = (num, fact = 1) => {
   if(num){
      return factorial(num-1, fact*num);
   };
   return fact;
};
const factorialArray = arr => arr.map(element => factorial(element));
console.log(factorialArray(arr));

Output

The output in the console will be −

[
   24,
   40320,
   2,
   5040,
   720,
   2432902008176640000,
   39916800,
   355687428096000,
   479001600,
   362880
]
raja
Published on 20-Aug-2020 06:42:05
Advertisements