How to make a function that returns the factorial of each integer in an array

Viewed 1469

This question has been deleted

4 Answers

First off, make a recursive function that calculates the factorial of a single number:

function factorial(num) {
    if (num == 0 || num == 1) {
        return 1;
    }
    return num * factorial(num - 1);
}

Then to do it for an array, just use Array.prototype.map() like so:

function getFactorials(arr) {
    var result = arr.map(x => factorial(x));
    return result;
}

Here's a demonstration:

 

function factorial(num) {
    if (num == 0 || num == 1) {
        return 1;
    }
    return num * factorial(num - 1);
}

function getFactorials(arr) {
    var result = arr.map(x => factorial(x));
    return result;
}

console.log(getFactorials([4, 8, 10])); 
console.log(getFactorials([]));
console.log(getFactorials([1, 2, 3, 4, 5]));

Hopefully this helps!

You need to separate function into two functions, one for iterating the array and collecting the calculated values and the other to get the facorial of a number.

function getFactorials(nums) {
    var result = [],
        i;
        
    for (i = 0; i < nums.length; i++) {
        result.push(getFactorial(nums[i]));
    }
    return result;
} 

function getFactorial(n) {
   if (n === 0 || n === 1) return 1;
   return n * getFactorial(n - 1);
}

console.log(getFactorials([]));
console.log(getFactorials([3]));
console.log(getFactorials([3, 4, 5]));
console.log(getFactorials([3, 8, 9, 10]));

This method will take an array of numbers and will return an array of factorial numbers of them,

function getFactorials(array) {
        var facArray = [];
        for (var j = 0; j < array.length; j++) {
            num = array[j];
            if (num === 0 || num === 1)
                return 1;
            for (var i = num - 1; i >= 1; i--) {
                num *= i;
            }
            facArray.push(num);
        }
        return facArray;

    }

console.log(getFactorials([4, 3, 2]));
function getFactorials(nums) {
  return numbers = Array.from(nums).map(function factorializeSingleNumber(num) {
    if (num == 0 || num == 1) return 1
    else return num * factorializeSingleNumber(num - 1)
  })
}

The best way I find of tackling these is to break the problem down. So in this case, work a solution that factorializes a single number. When that is working you can add this 'working code' into a map or loop, to work through the array.

My above solution uses recursion but could be a simple 'for loop' too

Related