Jake
Jake

Reputation: 149

How would I write a function that takes in an array of positive integers and returns an array of the factorials on the numbers?

I would like a function that takes in an array of positive integers and returns the factorials of those integers - using the .map or .reduce methods maybe?

e.g

[2, 4, 6] returns [2, 24, 720]

The below code works correctly when it is a single integer, but does not return anything when an array is passed.

function factorial(n) {
  if (n === 0) {
    return 1;
  } else {
    return n * factorial(n - 1);
  }
}

factorial(5); // 120

Upvotes: 2

Views: 305

Answers (2)

Nasir Khan
Nasir Khan

Reputation: 813

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value. See more

With .map() you can do it like this-

function factorialize(num) {
 if (num < 0) 
   return -1;
 else if (num == 0) 
   return 1;
 else {
   return (num * factorialize(num - 1));
 }
}
const numbers = [2,4,6];
const factorial = numbers.map(n => factorialize(n))
console.log(factorial)

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370989

Just call .map with your current function:

const factorial = (n) => {
  if (n === 0) {
    return 1;
  } else {
    return n * factorial(n - 1);
  }
}
const factorials = arr => arr.map(factorial);
console.log(factorials([2, 4, 6]));

Upvotes: 2

Related Questions