70

Prototype:

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

Anything similar to this in jQuery?

Harry
  • 87,580
  • 25
  • 202
  • 214
  • try this https://stackoverflow.com/questions/1159978/jquery-equivalent-to-prototype-array-last/69393531#69393531 – pankaj Sep 30 '21 at 13:57

13 Answers13

152

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];}
Salty
  • 6,688
  • 3
  • 33
  • 31
  • 1
    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 –  Jul 21 '09 at 15:47
  • 7
    Looks good to me. Why do you say it doesn't? The call to .split() ends chain-ability so no loss there. – Ken Browning Jul 21 '09 at 15:50
  • I agree with Ken. Plus, does that look better than: $('a').attr('href').split('#')[$('a').attr('href').split('#').length-1], haha. – Salty Jul 21 '09 at 15:53
  • 13
    This is wrong. If the array is empty, you are looking up `array[-1]` – DisgruntledGoat Apr 24 '11 at 16:32
  • 7
    @DisgruntledGoat ... which will return `undefined`. That's the same as Prototype's behavior: http://www.prototypejs.org/api/array/last – Jo Liss Nov 05 '11 at 00:22
  • 4
    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) – Sandwich Jan 20 '13 at 01:10
  • I don't know if anyone looks at this feed anymore, but you can now do: `array.pop();` to get the last one. – cbloss793 Jan 13 '15 at 18:33
84

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

guybrush
  • 1,579
  • 11
  • 5
  • 11
    Why not just `.slice().pop()` copy the array and pop an element off the copy? – gnarf Jul 22 '10 at 08:24
  • 1
    @gnarf I guess because copying all the array with `.slice()` can be more expensive than copying only the last element with `.slice(-1)` – Oriol Aug 07 '13 at 00:26
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];
gnarf
  • 105,192
  • 25
  • 127
  • 161
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.

Muhan Alim
  • 479
  • 1
  • 7
  • 17
  • 1
    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. – Pavel Lechev Mar 17 '15 at 16:13
  • 1
    This is wrong, [`.get() - Retrieve the DOM elements matched by the jQuery object.`](http://api.jquery.com/get/) . This is not meant to be used on an array like this. – Wesley Smith Oct 11 '16 at 22:14
  • 1
    @DelightedD0D You've answered the 'why not' part of my answer in that case. – Muhan Alim Oct 27 '16 at 12:51
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.

Manticore
  • 1,284
  • 16
  • 38
  • 1
    Reversing the array just to get the last value is unnecesary expensive. Also, the original array gets modified. – Sergi Ramón Jun 20 '12 at 08:04
  • Method still returns last element. So I do not see reason for downvotes. +1 here. – Pawka Jul 03 '12 at 09:41
  • 2
    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. – miguelsan Aug 06 '13 at 09:19
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.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
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
martin
  • 41
  • 1
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.

Jordan Gray
  • 16,306
  • 3
  • 53
  • 69
Michael Blackburn
  • 3,161
  • 1
  • 25
  • 18
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.

pankaj
  • 1
  • 17
  • 36
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

mtdb
  • 1,624
  • 2
  • 15
  • 18
  • 1
    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. – Michael Blackburn Jan 06 '14 at 15:37
  • 1
    @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](http://meta.stackexchange.com/a/164449)—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! :) – Jordan Gray Jan 06 '14 at 15:59
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

-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

fiedl
  • 5,667
  • 4
  • 44
  • 57
-1

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.

SevenJay
  • 9
  • 2
  • reverse the array and pick the first one of the reversed version, so the last one of the original – SevenJay Dec 15 '17 at 18:22
  • 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. – pixatlazaki Jan 23 '19 at 18:44