check for the last item in a javascript array
Solution 1
you can use .pop()
method:
console.log(myArray.pop()); // logs the last item
Array.prototype.pop() The pop() method removes the last element from an array and returns that element.
Simple test scenario:
var myArray = [{"a":"aa"},{"b":"bb"},{"c":"cc"}];
var last = myArray.pop();
console.log(last); // logs {"c":"cc"}
so now you can store it in a var and use it.
Solution 2
send index as parameter to the function
$.each(arr, function(index){
if(index == (arr.length - 1)){
// your code
}
});
Solution 3
Just add a second parameter to the function. This works both in jQuery and in native array.forEach method.
$.each(arr, function(item, i){
if (i === arr.length-1) doSomething(item);
});
arr.forEach(function(item, i){
if (i === arr.length-1) doSomething(item);
});
Solution 4
You can access both the index and current Array value within the $.each callback.
Warning: using .pop() as suggested in other answers will directly delete the last item from your array and return the value. Not good if you need the array again later.
// an Array of values
var myarray = ['a','b','c','d'];
$.each(myarray, function(i,e){
// i = current index of Array (zero based), e = value of Array at current index
if ( i == myarray.length-1 ) {
// do something with element on last item in Array
console.log(e);
}
});
Comments
-
Mohsen Shakiba almost 2 years
I have this array which I iterate through by using $.each(...). But I need to do something to the very last item in the array. so I need to know in the loop that if it's the last item, then do something. thanks a lot ;)