Derrick Omanwa
Derrick Omanwa

Reputation: 525

How to loop through a number by step but no exceed the number in javascript

I am new to javascript and I am attempting to create an array of numbers with a maximum and minumum value and step.I figured this would be straight forward. But I am not getting the desired array :

Here is my current code :

let list = []
let max = 27
let min = 10
let step = 10
for (let i = min; i <= max; i += step) {
  list.push(i);
}

This gives me an array of [10, 20, 30]

But I would like the last number in the array to be the max number. So the expected result would be an array of [10, 20, 27]

How would I achieve that? Thanks

Upvotes: 0

Views: 764

Answers (2)

Ranjeet Eppakayala
Ranjeet Eppakayala

Reputation: 3028

Try this using do ..while loop

let list = []
let i = 0
let max = 27
let min = 1
let step = 10

do {
  i++
  var item = i * step
  if (item >= max) item = max
  list.push(item);
} while (list[i - 1] < max)

console.log(list)

Upvotes: 1

Alexander Nied
Alexander Nied

Reputation: 13623

The problem is that you don't actually specify a limit on what goes into the array, only the limit of i at which point you want the loop to stop evaluating-- amd you are always pushing in the index (i) regardless of the max.

let list = []
let max = 27
let min = 10
let step = 10
for (let i = min; i <= max; i += step) {
  list.push(i);
}

console.log(list);

This actually yields [10, 20]; because after you push 20 in the next value of i is 30, which is lower than the max, so the loop exits.

If you want the max to be the highest value in the array but it doesn't divide evenly by your step size, you'll need to do some additional checks:

function fillArray(min, max, step) {
  const list = [];
  for (let i = min; i <= max; i += step) {
    list.push(i);
  }
  if (max % step !== 0) {
    list.push(max);
  }
  return list;
}

console.log(fillArray(10, 27, 10));

console.log(fillArray(0, 30, 5));

OR, as user @sp00m correctly points out, this can be improved to omit the if condition by changing the for condition:

function fillArray(min, max, step) {
  const list = [];
  for (let i = min; i < max; i += step) {
    list.push(i);
  }
  list.push(max);
  return list;
}

console.log(fillArray(10, 27, 10));

console.log(fillArray(0, 30, 5));

This doesn't handle all edge cases-- you could probably make it more robust.

Upvotes: 3

Related Questions