Search code examples
javascriptarraysfunctionmapreducefactorial

Factorializing a number with .reduce()


I am trying to write a function that will produce the factorial of a provided integer and then reduce the factorial array (by multiplying each array element).

For example:

factor(5) >>> [1, 2, 3, 4, 5] >>> 1 * 2 * 3 * 4 * 5 >>> 120

var array = [ ];

function factor(num) {
  for (i = 1; i <= num; i++) {
    array.push(i);
  }  
  array.reduce(function(a, b) {
    return a * b;
  })
};

factor(5);

However, it keeps returning undefined.

I think it has to do with the formatting of the function, but I'm not sure.


Solution

  • Try to pass the initial value for reduce,

    array.reduce(function(a, b) {
        return a * b;
    },1);
    

    Also return the reduced value of the array from the function,

    function factor(num) {
      for (i = 1; i <= num; i++) {
        array.push(i);
      }  
      return array.reduce(function(a, b) {
        return a * b;
      },1)
    };
    
    console.log(factor(5));