I have an array of numbers e.g. [2, 4, 5] and must get the factorials in a new array. E.g. [2, 24, 120]
I am using .map as you can see to perform the function on each integer in the array however, this does not work? I assume something is wrong with the recursive function?
Thanks.
function getFactorials(nums) {
if(nums > 1){
factarr = nums.map(x => x * (nums - 1));
}
return factarr;
}
You could take a function for the factorial and map the values.
The function has a recusive style with a check for the value. if the value is zero, then the function exits with one. Otherwise it returnd the product of the actual value and the result of the call of the function with decremented value.
The check uses an implict casting of a falsy to a boolean value for the conditional (ternary) operator ?:
.
const fact = n => n ? n * fact(n - 1) : 1;
var array = [2, 4, 5],
result = array.map(fact);
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With