Check for last iteration in jQuery.each
Solution 1
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);
};
Here's an additional example using the native forEach()
method:
data.forEach((val, i) => {
var isLastElement = index == data.length -1;
if (isLastElement) {
console.log('last item')
}
console.log(value);
});
Solution 2
the first parameter of the each function is equal to the index.
So, you can compare the index to the length of your data.
Look at this example using div tags :
$(document).ready(function(){
var len = $('div').length;
$('div').each(function(index){
if (index === (len - 1))
alert('Last index');
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>
Here's another example using an object that contain an array property :
var data = {
myArray:[1,2,3]
}
$(document).ready(function(){
var len = data.myArray.length;
$.each(data.myArray,function(index,value){
if (index === (len - 1))
alert(index);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Solution 3
You can check the length of data and compare it with the key (note that the first key is 0)
jQuery.ajax({
url: "<?php echo $this->getUrl('xs4arabia/index/getFetchrOrderLogs/'); ?>",
type: "GET",
data: {tracking_id: tracking_id},
dataType: "json",
success: function (data) {
var arrLength = data.length;
jQuery.each(data, function (key, value) {
if( key == arrLength - 1 ) {
/* this is the last one */
}
console.log(value);
},
})
![OBAID](https://i.stack.imgur.com/HH4hU.jpg?s=256&g=1)
OBAID
I am a Magento/PHP developer in a Leading Web Development Company. I have good skills and exprienced in Magento, Core PHP, MySql, Opencart, js, AJAX, PJAX. I have developed many extensions and also modified many magento core extensions.Integrated many shipping companies in magento like Fetchr,Aramex. Website About Me linkedin
Updated on July 05, 2022Comments
-
OBAID almost 2 years
How can we check for the last iteration of a
jQuery.each()
loop? My loop is iterating on an object coming from a$.ajax
request.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); }) } });