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 ;)
Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.
To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.
1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.
To get the last N elements of an array, call the slice method on the array, passing in -n as a parameter, e.g. arr. slice(-3) returns a new array containing the last 3 elements of the original array.
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.
send index as parameter to the function
$.each(arr, function(index){
if(index == (arr.length - 1)){
// your code
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With