catch forEach last iteration

JavascriptJquery

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

Updated answer for ES6+ is here.


arr = [1, 2, 3]; 

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

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.

Solution 2 - Javascript

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}` ); 
      }
    });

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJamie AndersonView Question on Stackoverflow
Solution 1 - JavascriptjdphenixView Answer on Stackoverflow
Solution 2 - JavascriptSterling BourneView Answer on Stackoverflow
Solution 3 - JavascriptJustin ColemanView Answer on Stackoverflow
Solution 4 - JavascriptUserOfStackOverFlowView Answer on Stackoverflow