Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check for the last item in a javascript array [duplicate]

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 ;)

like image 429
Mohsen Shakiba Avatar asked May 10 '14 10:05

Mohsen Shakiba


People also ask

How do you check if an item is repeated in an array Javascript?

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.

How do you check if an element in an array is repeated?

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.

How do you find the last thing in an array?

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.

How do you find the last two elements of an array?

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.


2 Answers

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.

like image 152
Jai Avatar answered Sep 26 '22 02:09

Jai


send index as parameter to the function

$.each(arr, function(index){
    if(index == (arr.length - 1)){
        // your code
    }
});
like image 21
Easwar Raju Avatar answered Sep 27 '22 02:09

Easwar Raju