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]));