How to select every 2nd element of an array in a for loop?
Use modulus(%)
operator to get every 2nd element
in loop and add fontStyle
on it:
var myList = document.getElementById('myList');var addList = ["Python", "C", "C++", "Ruby", "PHP", "Javascript", "Go", "ASP", "R"];
for (var i = 0; i < addList.length; i++) { var newLi = document.createElement("li"); newLi.innerHTML = addList[i]; if(i%2==0){ newLi.style.fontStyle = "italic" newLi.innerHTML = "<strong>"+addList[i]+"</strong>"; }
myList.appendChild(newLi);}
<ul id="myList"></ul>
Javascript: take every nth Element of Array
Maybe one solution :
avoid filter because you don't want to loop over 10 000 elements !
just access them directly with a for loop !
var log = function(val){document.body.innerHTML+='<div></pre>'+val+'</pre></div>'}
var oldArr = [0,1,2,3,4,5,6,7,8,9,10]var arr = [];
var maxVal = 5;
var delta = Math.floor( oldArr.length / maxVal );
// avoid filter because you don't want// to loop over 10000 elements !// just access them directly with a for loop !// |// Vfor (i = 0; i < oldArr.length; i=i+delta) { arr.push(oldArr[i]);}
log('delta : ' + delta + ' length = ' + oldArr.length) ;log(arr);
Selecting every nth item from an array
A foreach loop provides the fastest iteration over your large array based on comparison testing. I'd stick with something similar to what you have unless somebody wishes to solve the problem with loop unrolling.
This answer should run quicker.
$result = array();
$i = 0;
foreach($source as $value) {
if ($i++ % 205 == 0) {
$result[] = $value;
}
}
I don't have time to test, but you might be able to use a variation of @haim's solution if you first numerically index the array. It's worth trying to see if you can receive any gains over my previous solution:
$result = array();
$source = array_values($source);
$count = count($source);
for($i = 0; $i < $count; $i += 205) {
$result[] = $source[$i];
}
This would largely depend on how optimized the function array_values is. It could very well perform horribly.
Iterate over every nth element in string in loop - python
If you want to do something every nth step, and something else for other cases, you could use enumerate
to get the index, and use modulus:
sample = "This is a string"
n = 3 # I want to iterate over every third element
for i,x in enumerate(sample):
if i % n == 0:
print("do something with x "+x)
else:
print("do something else with x "+x)
Note that it doesn't start at 1 but 0. Add an offset to i
if you want something else.
To iterate on every nth element only, the best way is to use itertools.islice
to avoid creating a "hard" string just to iterate on it:
import itertools
for s in itertools.islice(sample,None,None,n):
print(s)
result:
T
s
s
r
g
How to start from second index for for-loop
First thing is to remember that python uses zero indexing.
You can iterate throught the list except using the range function to get the indexes of the items you want or slices to get the elements.
What I think is becoming confusing here is that in your example, the values and the indexes are the same so to clarify I'll use this list as example:
I = ['a', 'b', 'c', 'd', 'e']
nI = len(I) # 5
The range function will allow you to iterate through the indexes:
for i in range(1, nI):
print(i)
# Prints:
# 1
# 2
# 3
# 4
If you want to access the values using the range function you should do it like this:
for index in range(1, nI):
i = I[index]
print(i)
# Prints:
# b
# c
# d
# e
You can also use array slicing to do that and you don't even need nI
. Array slicing returns a new array with your slice.
The slice is done with the_list_reference[start:end:steps]
where all three parameters are optional and:start
is the index of the first to be included in the sliceend
is the index of the first element to be excluded from the slicesteps
is how many steps for each next index starting from (as expected) the start
(if steps
is 2 and start with 1 it gets every odd index).
Example:
for i in I[1:]:
print(i)
# Prints:
# b
# c
# d
# e
How do you select every nth item in an array?
You could also use step:
n = 2
a = ["cat", "dog", "mouse", "tiger"]
b = (n - 1).step(a.size - 1, n).map { |i| a[i] }
Related Topics
For Loop With Two Array in JavaScript
How to Count Unique Value from Object of Array in JavaScript
Show Multiple Divs on Button Click
Jquery Wait Until Ajax Call Has Got Data Before Displaying
How to Get the Id of a Button That Was Clicked - Reactjs
Window.Scroll Smooth Not Working on Safari
Uploading Multiple Files Using Formdata()
Counting Records in Json Array Using JavaScript and Postman
Auto Populate Field Base on What Was Entered in Another Field Simultaneously
How to Validate Mobile Number for Countries in Angular
Launch Chrome Browser from Internet Explorer
Save Only Date Without Timezone JavaScript
React Router Dom Returns a Blank Page When Going to a Particular Route
How to Instantiate a JavaScript Class in Another Js File
How to Deeply Remove Null Values, Empty Objects and Empty Array from an Object
How to Combine Object Values from Separate Lines into One Line