Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through arrays starting at different index while still looping through entire array?

Tags:

javascript

Suppose I had an array of 5 strings. How can I start a for loop at index 3 and go around and end up at index 2? Let me give an example.

var myArry = ["cool", "gnarly", "rad", "farout", "awesome"];

Would like to start at index 3 ("farout") loop through to end of array ("awesome") then continue looping at index 0 through index 2. Basically beginning an array at some point (other than index 0) and still hit every element in the array.

like image 799
dragonore Avatar asked Feb 10 '15 11:02

dragonore


People also ask

How do you iterate through an array in a for loop?

Iterating over an array You can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.

Which loop is used to iterate over arrays and strings?

The for..of loop in JavaScript allows you to iterate over iterable objects (arrays, sets, maps, strings etc).

Which control statement automatically loops over all the elements in the array without checking the array size?

“A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.

How do you loop around an array?

You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.


2 Answers

One way is to loop through the array using an index as normal, and use the modulus operator with your offset, to get a pointer to the correct place in the array:

var myArry = ["cool", "gnarly", "rad", "farout", "awesome"];
var offset = 3;
for( var i=0; i < myArry.length; i++) {
    var pointer = (i + offset) % myArry.length;
    console.log(myArry[pointer]);
}

So your loop is a standard loop through every element. You take the current position, plus offset, and get the remainder from that divided by the size of the array. Until you reach the end of the array that will just be the same as i + offset. When you reach the end of the array, the remainder will be zero, and go from there.

Here's a fiddle.

like image 149
James Waddington Avatar answered Sep 22 '22 10:09

James Waddington


Here's what you need:

var start = 3;
for(var z=0;z<myArry.length;++z) {
  var idx = (z+start) % myArry.length;
  console.log(myArry[idx]);
}
like image 20
Kokizzu Avatar answered Sep 22 '22 10:09

Kokizzu