Selecting last element in JavaScript array

1,247,747

Solution 1

How to access last element of an array

It looks like that:

var my_array = /* some array here */;
var last_element = my_array[my_array.length - 1];

Which in your case looks like this:

var array1 = loc['f096012e-2497-485d-8adb-7ec0b9352c52'];
var last_element = array1[array1.length - 1];

or, in longer version, without creating new variables:

loc['f096012e-2497-485d-8adb-7ec0b9352c52'][loc['f096012e-2497-485d-8adb-7ec0b9352c52'].length - 1];

How to add a method for getting it simpler

If you are a fan for creating functions/shortcuts to fulfill such tasks, the following code:

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

will allow you to get the last element of an array by invoking array's last() method, in your case eg.:

loc['f096012e-2497-485d-8adb-7ec0b9352c52'].last();

You can check that it works here: http://jsfiddle.net/D4NRN/

Solution 2

Use the slice() method:

my_array.slice(-1)[0]

Solution 3

You can also .pop off the last element. Be careful, this will change the value of the array, but that might be OK for you.

var a = [1,2,3];
a.pop(); // 3
a // [1,2]

Solution 4

use es6 deconstruction array with the spread operator

var last = [...yourArray].pop();

note that yourArray doesn't change.

Solution 5

var arr = [1, 2, 3];
arr.slice(-1).pop(); // return 3 and arr = [1, 2, 3]

This will return undefined if the array is empty and this will not change the value of the array.

Share:
1,247,747
mkyong
Author by

mkyong

Updated on May 29, 2021

Comments

  • mkyong
    mkyong almost 3 years

    I'm making an application that updates a user's location and path in real time and displays this on a Google Map. I have functionality that allows multiple users to be tracked at the same time using an object, which is updated every second.

    Right now, when a user pressed a button in the Android app, the coordinates are sent to a database and each time the location changes, a marker is updated on the map (and a polyline is formed).

    Since I have multiple users, I send a unique and randomly generated alphanumeric string so that I can display an individual path for each user. When the JS pulls this data from the database, it checks if the user exists, if it does not, it creates a new key with the value being a list. It would look something like this:

    loc = {f096012e-2497-485d-8adb-7ec0b9352c52: [new google.maps.LatLng(39, -86),
                                                  new google.maps.LatLng(38, -87),
                                                  new google.maps.LatLng(37, -88)],
           44ed0662-1a9e-4c0e-9920-106258dcc3e7: [new google.maps.LatLng(40, -83),
                                                  new google.maps.LatLng(41, -82),
                                                  new google.maps.LatLng(42, -81)]}
    

    What I'm doing is storing a list of coordinates as the value of the key, which is the user's ID. My program keeps updating this list each time the location is changed by adding to the list (this works properly).

    What I need to do is update the marker's location each time the location changes. I would like to do this by selecting the last item in the array since that would be the last known location. Right now, each time the location is changed a new marker is added to the map (each one of the points in the example would show a marker at that location) so markers continue to be added.

    I would use a ´for (x in loc)` statement each time the location updates to grab the last location from the list and use that to update the marker. How do I select this last element from the array within the hash?

  • Tadeck
    Tadeck over 12 years
    @LeviMorrison: In this case you can add a method to Array's prototype as well.
  • Tadeck
    Tadeck over 12 years
    @LeviMorrison: See my answer for the way that adds new method to all the arrays, so getting last element is easier.
  • Levi Morrison
    Levi Morrison over 12 years
    To be honest, if this is a critical part of his application, which it seems to be, he should be using objects, not just prototyping primitives. See my post.
  • Tadeck
    Tadeck over 12 years
    @LeviMorrison: Your answer is more about organizing the script / project, not about solving this specific issue. Adding (custom) function to the prototype may not be so clean, but let's be honest: arr[arr.length - 1] is the common and well-understood way of accessing last element of arr array.
  • Levi Morrison
    Levi Morrison over 12 years
    This is true, but I DO solve his problem, and hopefully I save him from some others by using objects. I'm not taking away from this solution at all. Prototyping can be very useful. I just don't think it's the best option here.
  • Tadeck
    Tadeck over 12 years
    @LeviMorrison: I do not say you do not solve the question. In fact, you do solve the question by a single line from your solution: return this.locations[this.locations.length - 1];. The rest is just a proposal on how to structure the script. And I totally agree with the way you organized this code - I use similar (or even the same) approach in even simple scripts I need to write for applications developed by me, even if the sole task is to add some UI effects / animations.
  • mkyong
    mkyong over 12 years
    This works like you said, but what I didn't realize is that it does not remove the old marker. How would I remove the previous marker each time?
  • Levi Morrison
    Levi Morrison over 12 years
    @Alex If you want to remove the previous marker, just use array.pop().
  • Tadeck
    Tadeck over 12 years
    @Alex: Which previous marker? The one just before the last one (the one at the position my_array.length - 2) or the one at the beginning of the array (the oldest one)?
  • mkyong
    mkyong over 12 years
    I'm trying to use this to reorganize my program. I'm new to JS, but this is much cleaner than what I currently have. Could you explain this a little bit? Like if I were to pull coordinates and a user ID from a database, how would I trigger the program? I am using AJAX to keep calling a program that pulls coordinates from my database.
  • Levi Morrison
    Levi Morrison over 12 years
    @Alex Basically, you would make an AJAX call to get the users and their locations. You then have a class or method of a class that translates it into the objects I define here. You could have a retreive or some other class that makes the ajax call and calls createUser and sets the locations properly. Does that make sense?
  • Admin
    Admin over 10 years
    Methods added to Array.prototype should be non-enumerable, so you should use Object.defineProperty
  • Erik  Reppen
    Erik Reppen about 10 years
    @nus That doesn't work in IE8. And that's basically covering for user-error (using for/in loops on arrays rather than forEach). Not sure how I feel about that, (IMO, in JS learning the "hard" way doesn't waste a lot of time typically) but it's debatable. The IE8 thing would be the main show-stopper for me on that strategy.
  • Jim Pivarski
    Jim Pivarski about 10 years
    This is a great answer! It can be used in a one-liner (my_array could be replaced by an expression or function that returns an array) and you don't have to make a global change to the Array prototype.
  • Stephen Quan
    Stephen Quan about 10 years
    +1 for the jsperf.com/get-last-item-from-array JavaScript performance link, however, for the browsers and computers I tried array[array.length - 1] did out perform array.slice(-1)[0] at least 40:1.
  • amay0048
    amay0048 about 10 years
    Just followed my own link and realised that I misread the graph :-P
  • Qix - MONICA WAS MISTREATED
    Qix - MONICA WAS MISTREATED about 10 years
    It's also extremely slow.
  • Sergey Yarotskiy
    Sergey Yarotskiy almost 10 years
    This code will fail if array is empty.
  • Tadeck
    Tadeck almost 10 years
    @SergeyYarotskiy: I do not agree with " This code will fail if array is empty ". If array is empty, the method will return undefined, which is more appropriate than any other value I can think of. Very simple, probably very fast, and resorts to standard behavior (using undefined when something is not found).
  • Casey Rodarmor
    Casey Rodarmor over 9 years
    Primitives are fine for simple operations. OO is not needed everywhere.
  • Domino
    Domino about 9 years
    You don't need to create a Users class for this - it could be static behavior in the User class. If you need more than one group of users to be managed individually, I would create a Group class, but I would never name a factory class as the plural form of its product. It becomes confusing, especially when you start naming instance variables "u", "user" and "users" in your code. Anyway, I would just use arrays in this case.
  • Sean Larkin
    Sean Larkin about 9 years
    Indeed this is extremely slow, you can reference jsperf.com/last-element-of-array-xxx
  • Josef Ježek
    Josef Ježek about 9 years
    Slowly, check out the test jsperf.com/last-element-of-array-xxx/2
  • Larta
    Larta about 9 years
    This is one way to do it right. Objects tends to make the code clear and easy to use. But something is wrong here : You don't use prototype for your function definition. This is bad for performance, always use the prototype property when defining functions. Else functions are added "on the fly" everytime you create this object.
  • Colin DeClue
    Colin DeClue almost 9 years
    @JosefJezek: Yeah, slower. But, I mean, you can still do like 200 million of these in one second, so probably best to worry about what's the most readable and not worry about performance, in this case. (Unless you're trying to do hundreds of millions of them a second, of course)
  • chris
    chris almost 9 years
    Its relatively slow, but not absolutely slow. ~100x slower than the alternative, but the slower version still executed nearly 10 million times a second in my browser.
  • chenghuayang
    chenghuayang over 8 years
    This is the most efficient way except array[elements-1], which is unpredictable with unknown numbers.
  • atlefren
    atlefren over 8 years
    "You shouldn't be using raw primitives to manage critical parts of your application." What is the rationale here?
  • Levi Morrison
    Levi Morrison over 8 years
    @atlefren Do a google search to learn about "primitive obsession".
  • atlefren
    atlefren over 8 years
    @LeviMorrison Well, I guess that is one standpoint. Although I disagree. The courses I took on progamming languages stressed the fact that functional programming languages tend to operate on primitives and sets/lists and dictionaries. This works perfectly fine, and as a consider JS more of a functional language than an OO one, I don't see the need to introduce "objects" just for the case of fulfilling someones opinion on programming in general
  • mjois
    mjois over 8 years
    I added a test case where you call .pop() and .push() consecutively. Seems to be 10x faster than .slice(-1)[0] but still 10x slower than direct access.
  • imrek
    imrek about 8 years
    This is not a safe way to use this.
  • Thaina Yu
    Thaina Yu almost 8 years
    Obviously it slow. slice create new array and pop modified array. Direct access just return
  • Marco Scabbiolo
    Marco Scabbiolo almost 8 years
    Please explain what your code is doing.
  • Blue
    Blue almost 8 years
    Welcome to Stack Overflow! While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations!
  • merrr
    merrr over 7 years
    Not to mention that the line is very obscure. I would hate to come across this in code.
  • neongrau
    neongrau over 7 years
    Actually pretty neat idea. Javascript reverse()does what you would expect and the last item becomes the first which you can address by [0]. It's a native function available in all browsers so speed shouldn't be an issue here. Caveat: developer.mozilla.org/en/docs/Web/JavaScript/Reference/… says it's mutating the Array. So further accessing the reversed Array might be not what you expected!
  • Dan Dascalescu
    Dan Dascalescu over 7 years
  • Dan Dascalescu
    Dan Dascalescu over 7 years
    Besides changing the array, this will also be extremely slow.
  • Josh from Qaribou
    Josh from Qaribou over 7 years
    This is the same as Array.prototype.slice(arr).pop();, which is duplicating the full array purely to get the last element.
  • Josh from Qaribou
    Josh from Qaribou over 7 years
    I like this. It's not going to be as fast as arr[arr.length - 1];, because you're instantiating a new array, but at least it's not some slow and/or destructive approach arr.reverse()[0] or [...arr].pop();, and you're not mutating a built-in prototype (very bad practice) like most of the other solutions. I'll add that nowadays you can use a destructured assignment and do away with the pop(), which may make sense in certain contexts. e.g. const arr = [1,2,3]; const [last] = arr.slice(-1);
  • Josh from Qaribou
    Josh from Qaribou over 7 years
    It's an old answer, but especially now please avoid mutating any builtin prototypes (e.g. Array.prototype.last = is an unsafe assignment).
  • ValarDohaeris
    ValarDohaeris over 7 years
    This is too hard to read
  • svarog
    svarog over 7 years
    if you worry about the array being mutated, reverse it back. very underrated answer!
  • Mox
    Mox over 7 years
    @svarog That only adds onto the time-complexity of the answer. Unnecessarily slow.
  • robert
    robert over 7 years
    Thanks for the contribution. The questions asks about "selecting" the last element. Selection implies that the array wasn't modified in the process. The .reverse() method will mutate (i.e., modify) the array, which is why I downvoted your answer.
  • Yola
    Yola about 7 years
    It is slower, but it is still a constant time.
  • Sajan
    Sajan about 7 years
    Thanks, i think this is the best solution and very useful for chain function like this data[rindex-1].url.split("/").reverse()[0].split(".")[0].tri‌​m();
  • Kalpesh Panchal
    Kalpesh Panchal about 7 years
    Looks short but definitely slower compared to other methods
  • chitti
    chitti over 6 years
    wouldn't this create a copy of yourArray, pop the last element and then throw the temporary copy away? I think this would be a costly operation if yourArray has a large number of elements.
  • Adam
    Adam over 6 years
    I’m not the first person to say this and I won’t be the last: Don’t modify objects you don’t own—especially not native prototypes. What happens when JavaScript comes around to implementing the same method name in ES spec but it’s slightly different from yours? Bad things. Prototype and Sugar.js both modify natives. In the end they’ve both cost me and the people I work with more time and money than they saved.
  • Manuel Romeiro
    Manuel Romeiro over 6 years
    Warning, the reverse() function will change the original array! var last = ['a', 'b', 'c']; last.reverse()[0]; last.toString(); will return "c,b,a"
  • magamig
    magamig almost 6 years
    @chitti or they just go to the last index and give you a copy of that element
  • MarredCheese
    MarredCheese over 5 years
    "So, a lot of people are answering with pop(), but most of them don't seem to realize that's a destructive method." Actually, all of them realize it's a destructive method. The answer you quoted notes it clearly in bold, while every other answer that involves pop makes a copy of the array first.
  • Anthony De Smet
    Anthony De Smet about 5 years
    If you're into the whole map reduce thing... try myArray.reduce((acc, curr) => curr, null). It saves you the trouble of referencing your array twice.
  • Vinay Pai
    Vinay Pai over 4 years
    This is a very bad solution... it doesn't just get the last element, it removes it from the array.
  • user1464581
    user1464581 over 4 years
    It's bad practice to modify the prototypes of objects you don't own.
  • newman
    newman about 4 years
    I always wondered why can't JavaScript reduce it from this.locations[this.locations.length-1] to this.locations[-1]. Wouldn't that make our life a little easier? Any reason not to?
  • ife
    ife about 4 years
    Just use arr.concat().pop()
  • Marcial Cahuaya
    Marcial Cahuaya almost 4 years
    Great, result is pertect .
  • Dennis Hackethal
    Dennis Hackethal almost 4 years
    Having a top-level fn like this answer suggests is better than adding a method to the prototype because it doesn't obscure access through encapsulation.
  • caiohamamura
    caiohamamura over 3 years
    For linear programmers this is not obscure at all.
  • Carl Smith
    Carl Smith over 3 years
    This also works when you don't have the array to begin with: indent = whitespace.split(newline).slice(-1)[0].length. Though pop may be better then: whitespace.split(newline).pop().length
  • Ekaitz Hernandez Troyas
    Ekaitz Hernandez Troyas over 3 years
    This is wrong if the array is only one element you get an empty array.
  • riv
    riv about 3 years
    @newman the reason not to is because it will break all code that relies on item at index -1 (or any other index outside of array bounds) being undefined, skipping explicit bounds checking.
  • vamsiampolu
    vamsiampolu almost 3 years
    I would suggest using the function on its now and avoid polluting the prototype. Also, non obvious way is const last = (arr) => arr.slice(-1)[0];
  • tnsaturday
    tnsaturday almost 2 years
    Not only it will mutate the original array, it's also an EXTREMELY costly operation as it includes recalculation of all the indexes in array!