Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through array with set intervals

Lets say you have a simple array like

var someArray = ["1" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9"];

Looping through the array like this

for (var i = 0; i < someArray.length; i++) {
        console.log(someArray[i]);
    };

gives this in the console......

1,2,3,4,5,6,7,8,9

....but is there a way of iterating through the array so that only nth items are selected? For example, 3nth values would give in the console

1, 4, 7, ........
like image 343
user1563944 Avatar asked Jan 06 '23 16:01

user1563944


2 Answers

Sure.

Your for iterator is actually composed of 3 parts. Declaration, condition and increment.

The increment is the 3rd parameter and most likely you've always just seen it as i++, but it can be anything. In your example, you'd want to increment i by 3, so i += 3.

for (var i = 0; i < someArray.length; i += 3) {
    console.log(someArray[i]);
};
like image 140
Scottie Avatar answered Jan 09 '23 06:01

Scottie


There is a simple technique involving the use of the modulo operator. You may use the following loop to achieve this if you do not wish to change by how much you increment i:

var someArray = ["1" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9"];

for (var i = 0; i < someArray.length; i++) {
    if( i % 3 === 0 ){
         console.log(someArray[i]);
    }
}

You may want to do this if you have other operations to perform on each element but would also like to perform specific operations on nth elements. You may replace the number 3 in my example with any number you like to represent the nth element value.

like image 26
vullnetyy Avatar answered Jan 09 '23 05:01

vullnetyy