Factorialize a Number - How can I do this using reduce()?

Tell us what’s happening:
How can I do this using reduce()?
If I can use the for loop and decrement the num till it is === to 1 and assign it to an array then use reduce() will it work?
I can’t do it so I’m asking to show me the code if it can be done.

Your code so far

function factorialize(num) {
  if(num === 0 || num === 1){
    return 1;
  }
  
  for(var i = num-1; i >= 1; i-- ){
    num*=i;
  }
  
  return num;
}

factorialize(5);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0.

Link to the challenge:
https://www.freecodecamp.org/challenges/factorialize-a-number

Here’s two approaches using reduce.

function factorialize(num) {
  var arr = []
  
  while(num > 0) {
    arr.push(num--)
  }

  return arr.reduce((accumulator, current) => {
    return accumulator * current;
  });
}
function factorialize(num) {
  return Array.apply(null, Array(num)).map((current, index) => {
    return index + 1;
  }).reduce((accumulator, current) => {
    return accumulator * current;
  });
}
1 Like

Both of the above solutions fail for factorialize(0).

const factorialize = n => n === 0 ? 1 : Array.from(new Array(n),(_,idx) => idx+1)
  .reduce((prod, val) => prod*val);
2 Likes