Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last key in array in javascript?

This is similar to this question,only PHP->javascript

How to get numeric key of new pushed item in PHP?

like image 326
user198729 Avatar asked Feb 04 '10 10:02

user198729


People also ask

How do I get the last key of an array?

The end() function is an inbuilt function in PHP and is used to find the last element of the given array. The end() function changes the internal pointer of an array to point to the last element and returns the value of the last element.

How do I find the last 5 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.

What is the last element in an array?

The Last element is nothing but the element at the index position that is the length of the array minus-1. If the length is 4 then the last element is arr[3].

How do I find the last key of an object?

To get the last item in an object, use the Object. keys() method to get an array of the object's keys and call the pop() method on the result, e.g. Object. keys(obj). pop() .


2 Answers

var foo = myarray[myarray.length - 1];

The preferred term is element, rather than key.

EDIT: Or do you mean the last index? That is myarray.length - 1. Keep in mind, JavaScript arrays can only be indexed numerically (though arrays are also objects, which causes some confusion).

like image 135
Matthew Flaschen Avatar answered Oct 05 '22 10:10

Matthew Flaschen


If it's a flat array, this would do:

return array.length - 1;

However, if you have an associative array, you'd have to know the key and loop through it. Please note though that JavaScript knows no such thing as an "associative array", as most elements in JavaScript are objects.

Disclaimer: Usage of associative arrays in JavaScript is generally not a good practice and can lead to problems.

var x = new Array();
x['key'] = "value";
for (i in x)
{
    if (i == 'key')
    {
        alert ("we got "+i);
    }
}
like image 25
Aron Rotteveel Avatar answered Oct 05 '22 12:10

Aron Rotteveel