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, ........
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]);
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With