Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factorialise all numbers in array with .map

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;
}
like image 363
SirNail Avatar asked Jan 26 '23 23:01

SirNail


1 Answers

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);
like image 64
Nina Scholz Avatar answered Feb 04 '23 20:02

Nina Scholz