sajad torkamani

You want a function that takes an integer and returns all its factors from one up to the number itself. Something like this:

getFactors(20) // [1, 2, 4, 5, 10, 20]
getFactors(121) // [1, 11, 121]

Here’s how:

function getFactors(num) {
  const factors = []

  for (let n = 1; n <= num; n++) {
    if (num % n === 0) {
      factors.push(n)
    }
  }

  return factors
}
Tagged: Snippets

Leave a comment

Your email address will not be published. Required fields are marked *