Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return the first n multiples of the number x

Tags:

javascript

Assuming that x is a positive integer, how would I return the first n multiples of the number x?

Here is what I have so far:

function multiples(x, n){
  var arr=[];
  for (var i=1; i<=x; ++i)
    arr.push(n*i);
  return arr;
}


console.log(
  multiples(2, 5)
  );

What I want it to return is this: multiples(2, 5) // [2, 4, 6, 8, 10]

But what it actually returns is this: [5, 10]

like image 227
Cody Wirth Avatar asked Dec 09 '25 00:12

Cody Wirth


2 Answers

You switched the x and the n in the for loop

//changed var to const & let

function multiples(x, n) {
  const arr = [];
  for (let i = 1; i <= n; i++)
    arr.push(x * i);
  return arr;
}

console.log(multiples(2, 5));

Using ES6 spread operator you can do like this:

function multiples(x, n) {
  return [...Array(n)].map((_, i) => x * ++i);
}

console.log(multiples(2, 5))

Using ES6 Array.from(...) you can do like this:

function multiples(x, n) {
  return Array.from(Array(n)).map((_, i) => x * ++i);
}

console.log(multiples(2, 5))
like image 70
dippas Avatar answered Dec 10 '25 13:12

dippas


x swap n

function multiples(x, n){
  var arr=[];
  for (var i=1; i<=n; ++i)
    arr.push(x*i);
  return arr;
}


console.log(
  multiples(2, 5)
);
like image 28
seunggabi Avatar answered Dec 10 '25 13:12

seunggabi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!