OBAID OBAID - 2 months ago 19
Javascript Question

check last iteration in .each jQuery

Sorry for my bad English.
How can we check last iteration of jQuery.each() loop. i want to check iteration of loop is last or not. My loop is iterating on an object coming from ajax success.

here is my code

jQuery.ajax({
url: "<?php echo $this->getUrl('xs4arabia/index/getFetchrOrderLogs/'); ?>",
type: "GET",
data: {tracking_id: tracking_id},
dataType: "json",
success: function (data) {
jQuery.each(data, function (key, value) {
console.log(value);
},
})

Answer

The first parameter passed to the each() handler function is the index of the current element in the array (although you've currently named it key). You can compare that to the length of the array to find out your current position:

$.each(data, function(index, value) {
    var isLastElement = index == data.length -1;

    if (isLastElement) {
        console.log('last item')
    }

    console.log(value);
},
Comments