There are multiple ways of finding out the last iteration of a for
and for...in
loop. But how do I find the last iteration in a for...of
loop. I could not find that in the documentation.
for (item of array) { if (detect_last_iteration_here) { do_not_do_something } }
The for-of loop, introduced in the sixth edition of EcmaScript (ES6), allows the programmer to loop over the actual iterable objects. This means that when used in an array, the variable used inside a for-of loop will return the element itself, and not the index.
The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present.
The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable string properties of an object, while the for...of statement iterates over values that the iterable object defines to be iterated over.
One approach is using Array.prototype.entries():
for (const [i, value] of arr.entries()) { if (i === arr.length - 1) { // do your thing } }
Another way is keeping a count outside the loop like Shidersz suggested. I don't think you want to check indexOf(item)
though because that poses a problem if the last item is duplicated somewhere else in the array...
One possible way is to initialize a counter outside the loop, and decrement it on every iteration:
const data = [1, 2, 3]; let iterations = data.length; for (item of data) { if (!--iterations) console.log(item + " => This is the last iteration..."); else console.log(item); }
.as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;}
Note that !--iterations
is evaluated as !(--iterations)
and the expression will be true
when iterations=1
.
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