0

I am trying to create an array with a variable gap between its values.

Eg.: supposing my gap equals 15, then my array will be [0, 15, 30, 45, 60].

This is what I have tried to do, but I couldn't make this work.

var min_array = 0;
var max_array = 60;
var gap = 15;

var arr = [];

while(min_array < max_array +1){
  arr.push(min_array+gap);
}

console.log(arr);

4 Answers 4

3

You have to count up min_array also with gap. Otherwise it will end in an infinity loop.

while(min_array < max_array){
  arr.push(min_array+gap);
  min_array += gap;
}
Sign up to request clarification or add additional context in comments.

Comments

2

Also, just as a heads up, the JS for loop can also do this pretty easily.
See this for the documentation.

var arr = [];
for (var i = 0; i <= 60; i+=15) {
    // Parameters: the first argument is your min_array, the next is your max_array, and the final is your gap.
    arr.push(i);
}

2 Comments

almost, just change i to start at 0
I upvoted everyone's answers, as all of them worked. But I marked yours as accepted because you were beyond the answer, simplifying it and attaching the documentation. Thank you, @Saber Nomen.
2

Edit your code to be like the code below , the problem with your code is that its runs for ever so you need to increase the min_array value every time you run the loop .

var min_array = 0;
var max_array = 60;
var gap = 15;

var arr = [];

while(min_array < max_array) {
  min_array = min_array+gap
  arr.push( min_array);
}

console.log(arr);

Comments

2

The previous answers are almost correct, but to include 0 do the following:

var min_array = 0;
var max_array = 60;
var gap = 15;

var arr = [];

while(min_array <= max_array){
  arr.push(min_array);
  min_array += gap;
}

console.log(arr);  // [0, 15, 30, 45, 60]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.