function factorialize(num) {
var myArray = [];
for(i = 1; i < num + 1; i++){
myArray.push(i);
}
myArray.reduce(function(a,b){return a*b;});
return myArray;
}
factorialize(5);
The section that creates the array tests fine when I console.log myArray. When I cut out the reduce method, it works fine when I substitute the array for the array name. For some reason, in my solution above, the reduce method will not pick up the values for myArray and returns undefined.
I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.
The function reduce does not change the array, it returns a value. And as pointed out, you are returning that unchanged array instead of the value that reduce created (and assigned to nothing). You can either return it directly like Jason suggests or you can (if you want for clarity) assign it to a variable…
var answer = myArray.reduce(function(a,b){return a*b;});
… and return that.
Jason’s approach is probably more common with experienced coders, but sometimes beginners like things broken up and clearer.