Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to make a function that returns the factorial of each integer in an array JavaScript
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
Creating the Factorial Function
First, we'll create a recursive function to calculate the factorial of a single number:
const factorial = (num, fact = 1) => {
if(num){
return factorial(num-1, fact*num);
};
return fact;
};
// Test the factorial function
console.log(factorial(5)); // 120
console.log(factorial(0)); // 1
120 1
Example: Complete Solution
Now we'll use the map() method to apply the factorial function to each element in the array:
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));
[
24,
40320,
2,
5040,
720,
2432902008176640000,
39916800,
355687428096000,
479001600,
362880
]
How It Works
The solution works in two parts:
- Recursive factorial function: Uses tail recursion with an accumulator parameter to calculate factorials efficiently
-
Array mapping: The
map()method creates a new array by applying the factorial function to each element
Alternative: Iterative Approach
Here's an iterative version for comparison:
const factorialIterative = (num) => {
if (num arr.map(element => factorialIterative(element));
console.log(factorialArrayIterative(arr));
[6, 24, 120]
Conclusion
Using map() with a factorial function provides an elegant solution to calculate factorials for all array elements. The recursive approach with tail recursion is memory-efficient for this use case.
