freeCodeCamp Challenge Guide: Factors of an integer

Factors of an integer


Solutions

Solution 1 (Click to Show/Hide)
function factors(num) {
  const arr = [];
  for (let i = 2; i <= num/2; i++) {
    if (num % i === 0) {
      arr.push(i);
    }
  }
  return [1, ...arr, num]; 
}
Solution 2 (Click to Show/Hide)
function factors(num) {
  return Array
    .from(Array(num + 1), (_, i) => i)
    .filter(i => num % i === 0)
}

This solution uses ES6. Using the Array class, create an array whose length is equal to n + 1. Use the Array.from method to replace every every array element with its index value. Since this is initially an empty array, we use _ as the item parameter to show that this parameter is not needed when we replace the values.

Then, implement a filter using Array.filter. For each array element, we check if it divides num using num % i . If it does, i is a factor, and it stays in the array.

2 Likes