- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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 ]
Advertisements