72

Prototype:

var array = [1,2,3,4];
var lastEl = array.last();

Anything similar to this in jQuery?

1

13 Answers 13

153

Why not just use simple javascript?

var array=[1,2,3,4];
var lastEl = array[array.length-1];

You can write it as a method too, if you like (assuming prototype has not been included on your page):

Array.prototype.last = function() {return this[this.length-1];}
Sign up to request clarification or add additional context in comments.

7 Comments

because something like the following will not look good: $('a').attr('href').split('#').last(); <-- of course last() is not a jquery function here... it's just to make an example
Looks good to me. Why do you say it doesn't? The call to .split() ends chain-ability so no loss there.
This is wrong. If the array is empty, you are looking up array[-1]
@DisgruntledGoat ... which will return undefined. That's the same as Prototype's behavior: prototypejs.org/api/array/last
You didn't answer his question. Yes, raw javascript may be superior, but the question was a jQuery equivalent. Your proposed solution may produce undesired circumstances in some jQuery scenarios (experienced one myself)
|
85

with slice():

var a = [1,2,3,4];
var lastEl = a.slice(-1)[0]; // 4
// a is still [1,2,3,4]

with pop();

var a = [1,2,3,4];
var lastEl = a.pop(); // 4
// a is now [1,2,3]

see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array for more information

2 Comments

Why not just .slice().pop() copy the array and pop an element off the copy?
@gnarf I guess because copying all the array with .slice() can be more expensive than copying only the last element with .slice(-1)
22

When dealing with a jQuery object, .last() will do just that, filter the matched elements to only the last one in the set.

Of course, you can wrap a native array with jQuery leading to this:

var a = [1,2,3,4];
var lastEl = $(a).last()[0];

Comments

12

Why not use the get function?

var a = [1,2,3,4];
var last = $(a).get(-1);

http://api.jquery.com/get/ More info

Edit: As pointed out by DelightedD0D, this isn't the correct function to use as per jQuery's docs but it does still provide the correct results. I recommend using Salty's answer to keep your code correct.

3 Comments

Given the question asked, I think this is the most relevant and elegant answer. As per jQuery docs: "A negative index is counted from the end of the matched set, so this example returns the last item in the list:" Thanks.
This is wrong, .get() - Retrieve the DOM elements matched by the jQuery object. . This is not meant to be used on an array like this.
@DelightedD0D You've answered the 'why not' part of my answer in that case.
3

I know the answer is already given, but I think I've got another solution for this. You could take the array, reverse it and output the first array item like this:

var a = [1,2,3,4];
var lastItem = a.reverse()[0];

Works fine for me.

3 Comments

Reversing the array just to get the last value is unnecesary expensive. Also, the original array gets modified.
Method still returns last element. So I do not see reason for downvotes. +1 here.
Boy, your processor needs more work for the same result. It is a waste of resources without gain. Can't you see that? That "Just Works For Me" is a ridiculous mantra.
2

For arrays, you could simply retrieve the last element position with array.length - 1:

var a = [1,2,3,4];

var lastEl = a[a.length-1]; // 4

In jQuery you have the :last selector, but this won't help you on plain arrays.

Comments

2

If u use the prototype on arrays like:

Array.prototype.last = function() {return this[this.length-1];}

using forloops will do this.

var a = [0,1,2];
out --> 0
out --> 1
out --> 2
out --> last

1 Comment

you should use hasOwnProperty to avoid this.
1

According to jsPerf: Last item method, the most performant method is array[array.length-1]. The graph is displaying operations per second, not time per operation.

It is common (but wrong) for developers to think the performance of a single operation matters. It does not. Performance only matters when you're doing LOTS of the same operation. In that case, using a static value (length) to access a specific index (length-1) is fastest, and it's not even close.

Comments

1

You can use this Arr.slice(-1)[0].

Arr=[1,2,3,4,5,6,7]

Lets understand this. -1 means you are looking last index of Array. so when you use Arr.slice(-1)[0] then you will get result : 7.

Comments

0

See these test cases http://jsperf.com/last-item-method The most effective way is throug .pop method (in V8), but loses the last element of the array

2 Comments

Lots of talk about this way or that way being more performant, someone posts a link demonstrating performance, and no upvotes. Of course that's probably because he read the graph backwards. I've corrected & extended his comments.
@MichaelBlackburn Hey! I spotted your edit in the review queue and thought I should explain why it was rejected despite being more accurate. Simply: edits shouldn't change the content of a post, even to fix factual errors—instead, it's best to downvote such answers and leave a comment explaining why. You are absolutely correct, of course, so perhaps you could add your own answer with accurate performance information? I'd upvote it! :)
0

url : www.mydomain.com/user1/1234

$.params = window.location.href.split("/"); $.params[$.params.length-1];

You can split based on your query string separator

Comments

0

I use this:

array.reverse()[0]

You reverse the array with reverse() and then pick the first item of the reversed version with [0], that is the last one of the original array.

You can use this code if you don't care that the array gets reversed of course, because it will remain so.

2 Comments

reverse the array and pick the first one of the reversed version, so the last one of the original
This is O(n) as it will reverse the entire array, even if you just need the last entry. Salty's answer is O(1), which is faster as the array gets long.
-1

SugarJS

It's not jQuery but another library you may find useful in addition to jQuery: Try SugarJS.

Sugar is a Javascript library that extends native objects with helpful methods. It is designed to be intuitive, unobtrusive, and let you do more with less code.

With SugarJS, you can do:

[1,2,3,4].last()    //  => 4

That means, your example does work out of the box:

var array = [1,2,3,4];
var lastEl = array.last();    //  => 4

More Info

Comments

Your Answer

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