Jamie Anderson
Jamie Anderson

Reputation: 1493

catch forEach last iteration

arr = [1,2,3];
arr.forEach(function(i){
// last iteration
});

How to catch when the loop ending? I can do if(i == 3) but I might don't know what is the number of my array.

Upvotes: 136

Views: 187468

Answers (4)

jdphenix
jdphenix

Reputation: 15415

See also an updated answer for ES6+.


arr = [1, 2, 3]; 

arr.forEach(function(elem, idx, array){
   if (idx === array.length - 1){ 
       console.log("Last callback call at index " + idx + " with value " + elem ); 
   }
});

would output:

Last callback call at index 2 with value 3

The way this works is testing arr.length against the current index of the array, passed to the callback function.

Upvotes: 262

UserOfStackOverFlow
UserOfStackOverFlow

Reputation: 108

I prefer this way:

arr.forEach(function(i, idx, array){
   if (idx + 1 === array.length){ 
       console.log("Last callback call at index " + idx + " with value " + i ); 
   }
});

Seems Like more positive

Upvotes: 5

Sterling Bourne
Sterling Bourne

Reputation: 3342

The 2021 ES6+ ANSWER IS:

    const arr = [1, 2, 3];

    arr.forEach((val, key, arr) => {
      if (Object.is(arr.length - 1, key)) {
        // execute last item logic
        console.log(`Last callback call at index ${key} with value ${val}` ); 
      }
    });

Upvotes: 46

Justin Coleman
Justin Coleman

Reputation: 134

const arr= [1, 2, 3]
arr.forEach(function(element){
 if(arr[arr.length-1] === element){
  console.log("Last Element")
 }
})

Upvotes: 6

Related Questions