Pages

Friday, August 11, 2017

catch forEach last iteration

Find last iteration in forEach in nodejs

We can iterate an array, either via loop or forEach

Via Loop:

var arr= [ 1, 2, 3, 4 ];

for(var i =0;i < arr.length ; i++ ){
console.log( arr [ i ] );
}


Via forEach

var arr= [ 1, 2, 3, 4 ];
arr.forEach( function ( element ) { 
 console.log( element );
}

How to find the last iteration in for Each ?

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 ); 
   }
});
 
Reference:
https://stackoverflow.com/questions/29738535/catch-foreach-last-iteration
 

No comments:

Post a Comment