15

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

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

6 Answers 6

20
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).

1
  • 5
    @user198729 Arrays in JavaScript work differently than PHP. PHP implements them as sparse arrays which is why the index of the first/last element aren't always 0/len-1. In JavaScript all arrays are dense arrays, zero-base, fully populated (maybe undefined) index elements from 0 to .length-1.
    – nicerobot
    Feb 4, 2010 at 11:24
6

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);
    }
}
4
  • 1
    Why use an Array? You're not using the arrayness of it (i.e. the magic length property) so you might as well use an Object. Also, the JavaScript spec makes no guarantee about the order of the keys when using a for...in loop, so there's no such thing as the "last key"
    – Tim Down
    Feb 4, 2010 at 11:41
  • In the first example, I used the length property. Since this property is not available on associative arrays, I added the second example, which cleary demonstrates a use case of a "simulated last key". Since the OP would know the name of the last key, it would be possible to get the actual element with the above method. Feb 4, 2010 at 12:10
  • Re. the length property, I was referring to the second example, not the first.
    – Tim Down
    Feb 5, 2010 at 9:27
  • Ah, I understand. OP specifically asked how to get a key in an Array, so that's why (even though it is technically still an Object). There are probably more refined ways to do this. Feb 5, 2010 at 10:13
4

I assume your array is a "key associated array" with string keys in number format. You will need to do it in 3 steps:

  1. Get all array keys.
  2. Convert array keys to an integer.
  3. Get max or length or any other keys property.
stringKeys = Object.keys(keyValueArray); // Get keys of array 
integerKeys = stringKeys.map(Number); // Convert to integer
mx = Math.max.apply(integerKeys); // Get max
len = stringKeys.length; // Get length 

Hope I helped

1
  • then to answer the original question of what is the last key in the associative array I had to do : stringKeys[len-1] or if you want an integer integerKeys[len-1].
    – Kev Price
    Nov 7, 2017 at 13:04
2

The last key of an array is always arr.length-1 as arrays always start with key 0:

var arr = new Array(3);  // arr === [], arr.length === 3
arr.push(0);             // arr === [undefined, undefined, undefined, 0], arr.length === 4
arr[arr.length-1]        // returns 0

var arr = [];            // arr === [], arr.length === 0
arr[3] = 0;              // arr === [undefined, undefined, undefined, 0], arr.length === 4
arr[arr.length-1]        // returns 0
2

If your array is an associative array(Object), I think the best way to do this is by using Object.keys().

From MDN;

The Object.keys() method returns an array of a given object's own property names, in the same order as we get with a normal loop.

First get the keys of the array in an numeric array.
Then get the last key, and use it in the Object.

var keys = Object.keys(my_array);
var last = keys[keys.length - 1];
console.log(my_array[last]);
0
Math.max(...[...myArray.keys()]);

Here myArray is the name of an array.

This is a solution based on your referred question. Assuming the array is a single dimensional array or all the array keys are numeric.

Reads: Math.max, Array.prototype.keys(), Iterators and generators

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.