1

Not too sure where I've gone wrong here, expecting to factorialize 5 (1*2*3*4*5 = 120) by turning 5 into a string of [1,2,3,4,5] and then using reduce to multiply the string all together. When I run the code, it just gives me [1,2,3,4,5]...

 var arr = [];

function factorialize(num) {

 for (var i = 1; i <= num; i++) {
  arr.push(i);
}
  return arr;
}

var factors = 0;

factors = arr.reduce(function(previousVal, currentVal) {
  return previousVal * currentVal;
}, 0); // Expecting 120, instead result = [1,2,3,4,5]

factorialize(5);

Forgive the long route - my first week of Javascript!

2
  • 1
    Actually, factors = 0 because arr is empty when you call reduce on it Commented Mar 22, 2018 at 14:50
  • "..by turning 5 into a string of [1,2,3,4,5]..." - I think you mean you turned it into an array -- that's what the data type of a number of comma separated values between square-brackets ([]) are called. A string is a different datatype (text between quotes). Commented Mar 22, 2018 at 14:52

6 Answers 6

2

arr is empty, you should give it the resulting array of the factorisation first, and you should multiply, not add, and when multiplying, the starting value is 1 not 0:

var arr = [];

function factorialize(num) {
  for (var i = 1; i <= num; i++) {
    arr.push(i);
  }
  return arr;
}

arr = factorialize(5); // give it the value

var factors = arr.reduce(function(previousVal, currentVal) {
  return previousVal * currentVal; // multiply, don't add
}, 1); // start with 1 when multiplying

console.log(arr);
console.log(factors);

If you just want to calculate the factorial:

function factorial(num) {
  var res = 1;
  for (var i = 2; i <= num; i++) {
    res *= i;
  }
  return res;
}
console.log('factorial(5) = ' + factorial(5));
console.log('factorial(10) = ' + factorial(10));

Sign up to request clarification or add additional context in comments.

4 Comments

How can I make this into an algorithm where I can have factorialize(5); not in arr? if I have arr = factorialize(num); then I havent defined num?
@daggett You mean you want factorialize(5); to return 120?
yes I want to enter the factorialized number outside of arr
@daggett Check my edit, see if the function factorial(n) I added does what you want.
1

You are not calling factors. factorialize(5); by doing this you are just calling function factorialize(num) which will give you array(of 1...num).

(Additional info)And also in reduce you are adding + instard of multiplying * so change that too and

factors = arr.reduce(function(previousVal, currentVal) {
  return previousVal + currentVal;
}, 0);
   ^
   |_  either initialize it to 1 or remove this.

See below code. I just create array and then apply reduce on that array.

function factorialize(num) {
 var arr = [];
 for (var i = 1; i <= num; i++) {
  arr.push(i);
 }
 return arr.reduce(function(previousVal, currentVal) {
      return previousVal * currentVal;
  });
}


console.log(factorialize(5));

1 Comment

This is what I was trying to do - didn't realise I could use reduce on the return
1
var arr = [];
function factorialize(num) {
    for (var i = 1; i <= num; i++) {
        arr.push(i);
    }
    var factors = 0;
    factors = arr.reduce(function (previousVal, currentVal) {
        return previousVal * currentVal;
    });
    return factors
}

factorialize(5); // 120

1 Comment

Provide some explanation with the answer.
1

You could get first the factors and then multiply in Array#reduce the factors.

I suggest to name the function what it does and move the array declaration inside of the function, because the function returns this array.

For getting the product, you need to multiply the values and use 1 as neutral start value for getting a product out of the numbers.

function getFactors(num) {
    var i, arr = [];

    for (i = 1; i <= num; i++) {
        arr.push(i);
    }

    return arr;
}

var factors = getFactors(5),
    product = factors.reduce(function(previousVal, currentVal) {
        return previousVal * currentVal;
    }, 1);

console.log(factors);
console.log(product);

2 Comments

+1 for being the first answer to bring var arr=[]; into the function. However I would suggest taking the factors= and the product= lines apart, and logging factors between the two - that would be easier to follow for a beginner.
right, you could do so, but factors is not mutating later.
0
  • Put the global variable arr inside of the function factorialize.
  • Get the returned array and then execute the function reduce.
  • You need to multiply rather than to add the numbers.
  • Start the reduce with initialValue = 1, this is to avoid 0 * n.

function factorialize(num) {
  var arr = [];
  for (var i = 1; i <= num; i++) {
    arr.push(i);
  }
  return arr;
}

var arr = factorialize(5);
var factors = arr.reduce(function(previousVal, currentVal) {
  return previousVal * currentVal;
}, 1);

console.log(factors)

Comments

0

Issue is with the initial value set to 0 and instead of multiplying numbers, it is being added

arr.reduce(callback, initValue)

arr = [1,2,3,4,5]

In the code provided, it accumulates in below format

arr.reduce(function(previousVal, currentVal) {
  return previousVal + currentVal;
}, 0);

First call -> 0 + 1 = 1 (factors = 1)
Second call -> 0 + 2 = 2 (factors = 2)
First call -> 0 + 3 = 3 (factors = 3)
First call -> 0 + 4 = 4 (factors = 10)
First call -> 0 + 5 = 5 (factors = 15)

To achieve expected result, use below option

var arr = []; // initialize array arr

function factorialize(num) {
//for loop to push 1,2 ,3, 4, 5 to arr array
 for (var i = 1; i <= num; i++) {
  arr.push(i);
}
// return arr.reduce value by multiplying all values in array, default initial value is first element 
  return arr.reduce(function(previousVal, currentVal) {
  //console log to debug and display loop values
  console.log(previousVal, currentVal);
  return previousVal * currentVal;
});
}

console.log("output", factorialize(5));

code sample - https://codepen.io/nagasai/pen/YaQKZw?editors=1010

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.