Javascript smallest common multiple - reduce method not working

I’m trying to use the reduce() method in order to get the smallest common multiple of all the numbers in the seq array, but for some reason, it keeps returning undefined. Anybody know what’s going on here?

function smallestCommons(arr) {
arr.sort((a,b)=>a-b)
let seq = []
for (let i=arr[0];i<=arr[1];i++) {
  seq.push(i)
}

return seq.reduce((a,b) => {
  (a*b)/gcd(a,b)
})
}



function gcd(a,b) {
if (b==0) {
  return a
}
else {
  return (b,a%b)
}
}

smallestCommons([1,5]);

Browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:103.0) Gecko/20100101 Firefox/103.0

Challenge: Intermediate Algorithm Scripting - Smallest Common Multiple

Link to the challenge:

This line can’t be correct.


You never return anything from the callback function.


Formatting for readability:

function smallestCommons(arr) {
  arr.sort((a, b) => a - b);
  const seq = [];
  for (let i = arr[0]; i <= arr[1]; i++) {
    seq.push(i);
  }

  return seq.reduce((a, b) => 
    (a * b) / gcd(a, b)
  })
}



function gcd(a, b) {
  if (b === 0) {
    return a;
  } else {
    return (b, a % b);
  }
}

console.log(smallestCommons([1, 5]));

Thanks. I can’t believe I missed that!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.