Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect last iteration in FOR OF loop in ES6 javascript

Tags:

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     } } 
like image 782
Vlad Otrocol Avatar asked Jan 09 '19 19:01

Vlad Otrocol


People also ask

Is for of loop ES6?

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.

How do you check if an item is last in an array?

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.

What is difference between Forin and for OF in JavaScript?

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.


2 Answers

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...

like image 115
J S Avatar answered Sep 17 '22 12:09

J S


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.

like image 24
Shidersz Avatar answered Sep 18 '22 12:09

Shidersz