15

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
    }
}
Penny Liu
  • 7,720
  • 5
  • 40
  • 66
Vlad Otrocol
  • 2,214
  • 6
  • 27
  • 51
  • 3
    This is not really possible - an iterator could be infinite. You only know whether it is the last element after checking for the next. What exactly do you need this for? – Bergi Jan 09 '19 at 19:21

6 Answers6

18

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.

Shidersz
  • 15,614
  • 2
  • 15
  • 40
18

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

J S
  • 678
  • 3
  • 6
2

You could slice the array and omit the last element.

var array = [1, 2, 3],
    item;
    
for (item of array.slice(0, -1)) {
    console.log(item)
}
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
1

If you want to change your loop behavior based the specific index, then it's probably a good idea to use an explicit index in your for-loop.

If you simply want to skip out on the last element, you can do something like

for (item of array.slice(0, -1)) {
    //do something for every element except last
}
Matt H
  • 1,035
  • 5
  • 8
1

The simpliest way to find the last loop and, let's say, get rid of the last comma insert during iterration is to compare the length of array with the index of its last item.

const arr = ["verb", "noun", "pronoun"];

for (let item of arr) {
    if (arr.length -1 !== arr.indexOf(item)) {
        console.log('With Commas');
    } else {
        console.log('No Commars');
    }
}
Maksym Dudyk
  • 71
  • 2
  • 8
0

There doesnt seem to be anything the the spec for for..of for this. There seems to be two work-arounds:

If you can, just push a marker to the end of the array and act on that marker, like so:

myArray.push('FIN')
for (el of myArray){
    if (el === 'FIN')
        //ending code
}

Alternatively, you can use the below to get an index you can use in tandem with an Array.length

enter link description here

Thomas Skubicki
  • 378
  • 2
  • 8