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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With