Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 599
GoMagikarp Avatar asked Mar 03 '16 19:03

GoMagikarp


1 Answers

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));
like image 200
Rajaprabhu Aravindasamy Avatar answered Oct 16 '22 09:10

Rajaprabhu Aravindasamy