Possible to improve with another Array method?

Possible to improve with another Array method?
0.0 0

#1

Hello! I finally finished a challenge of finding the LCM of an array of values that’s on FCC. I have the impression in my mind that it’s possible to do some of this with an array method (like reduce(), or filter()) but I don’t have a lot of experience with those. I was wondering if anyone out there was willing to take a look at my solution and see if a portion was possible to refactor with one of those methods? I feel like if I see something I wrote refactored using one of those methods I might better be able to understand them.

Anyway, here it is. I commented out a few of the first few functions because I initially had an that involved determining if numbers were prime and finding prime factorization, but ended up going another route.

It’s also on my codepen: https://codepen.io/ryanmdoyle/pen/oyJNKR

function getLCM(num1, num2) {
  for (let i = 1; i <= num2; i++) {
    if (num1*i % num2 == 0) {
      return num1*i;
    }
  }
  return 1;
}

function smallestCommons(arr) {
  arr.sort((a, b) => {
    return a-b;
  });

  let range = [];
  for (let i = arr[0]; i <= arr[1]; i++) { // make a range for the numbers in argument
    range.push(i);
  }
  
  let LCM = 1;
  for (let i = 0; i < range.length; i++) {
    LCM = getLCM(LCM, range[i]);
  }
  return LCM
}
console.log(smallestCommons([1, 5]));
console.log(smallestCommons([5, 1]));
console.log(smallestCommons([2, 10]));
console.log(smallestCommons([1, 13]));
console.log(smallestCommons([23, 18]));

#2

javascript

function getLCM(num1, num2) {
  for (let i = 1; i <= num2; i++)
    if (num1 * i % num2 == 0)
      return num1*i;

  return 1;
}

function smallestCommons(arr) {
  const min = Math.min(...arr);
  const max = Math.max(...arr);

  let LCM = 1;

  for (let i = min; i <= max; i++)
    LCM = getLCM(LCM, i);

  return LCM;
}

You don’t actually need a loop to create the range and another loop to iterate it. You can do it with just one loop
:slight_smile:


#3

@ryanmdoyle and @jlouiss Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.


#4

Thank you! I’ll be sure to do that in the future.