[javascript] Selecting last element in JavaScript array

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?

This question is related to javascript arrays google-maps google-maps-markers

The answer is


So, a lot of people are answering with pop(), but most of them don't seem to realize that's a destructive method.

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

So, for a really silly, nondestructive method:

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

a push pop, like in the 90s :)

push appends a value to the end of an array, and returns the length of the result. so

d=[]
d.push('life') 
//=> 1
d 
//=>['life']

pop returns the value of the last item of an array, prior to it removing that value at that index. so

c = [1,2,1]
c.pop() 
//=> 1
c 
//=> [1,2]

arrays are 0 indexed, so c.length => 3, c[c.length] => undefined (because you're looking for the 4th value if you do that(this level of depth is for any hapless newbs that end up here)).

Probably not the best, or even a good method for your application, what with traffic, churn, blah. but for traversing down an array, streaming it onto another, just being silly with inefficient methods, this. Totally this.


Underscore and Lodash have the _.last(Array) method, that returns the last element in an Array. They both work about the same

_.last([5, 4, 3, 2, 1]);
=> 1

Ramda also has a _.last function

R.last(['fi', 'fo', 'fum']); //=> 'fum'

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.


var last = array.slice(-1)[0];

I find slice at -1 useful for getting the last element (especially of an array of unknown length) and the performance is much better than calculating the length less 1.

Mozilla Docs on Slice

Performance of the various methods for selecting last array element


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]

In case you are using ES6 you can do:

const arr = [ 1, 2, 3 ];
[ ...arr ].pop(); // 3
arr; // [ 1, 2, 3 ] (wasn't changed)

Use the slice() method:

my_array.slice(-1)[0]

This worked:

array.reverse()[0]

You can define a getter on Array.prototype:

_x000D_
_x000D_
if (!Array.prototype.hasOwnProperty("last")) {_x000D_
  Object.defineProperty(Array.prototype, "last", {_x000D_
    get() {_x000D_
      return this[this.length - 1];_x000D_
    }_x000D_
  });_x000D_
}_x000D_
_x000D_
console.log([9, 8, 7, 6].last); // => 6
_x000D_
_x000D_
_x000D_

As you can see, access doesn't look like a function call; the getter function is called internally.


var last = function( obj, key ) { 
    var a = obj[key];
    return a[a.length - 1];
};

last(loc, 'f096012e-2497-485d-8adb-7ec0b9352c52');

use es6 deconstruction array with the spread operator

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

note that yourArray doesn't change.


Use JavaScript objects if this is critical to your application. You shouldn't be using raw primitives to manage critical parts of your application. As this seems to be the core of your application, you should use objects instead. I've written some code below to help get you started. The method lastLocation would return the last location.


function User(id) {
    this.id = id;

    this.locations = [];

    this.getId = function() {
        return this.id;
    };

    this.addLocation = function(latitude, longitude) {
        this.locations[this.locations.length] = new google.maps.LatLng(latitude, longitude);
    };

    this.lastLocation = function() {
        return this.locations[this.locations.length - 1];
    };

    this.removeLastLocation = function() {
        return this.locations.pop();
    };

}

function Users() {
    this.users = {};

    this.generateId = function() {
        return Math.random();
    };

    this.createUser = function() {
        var id = this.generateId();
        this.users[id] = new User(id);
        return this.users[id];
    };

    this.getUser = function(id) {
        return this.users[id];
    };

    this.removeUser = function(id) {
        var user = this.getUser(id);
        delete this.users[id];

        return user;
    };

}


var users = new Users();

var user = users.createUser();

user.addLocation(0, 0);
user.addLocation(0, 1);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to google-maps

GoogleMaps API KEY for testing Google Maps shows "For development purposes only" java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion How to import JSON File into a TypeScript file? Googlemaps API Key for Localhost Getting "Cannot call a class as a function" in my React Project ERROR: Google Maps API error: MissingKeyMapError This page didn't load Google Maps correctly. See the JavaScript console for technical details Google Maps API warning: NoApiKeys ApiNotActivatedMapError for simple html page using google-places-api

Examples related to google-maps-markers

How to change icon on Google map marker Auto-center map with multiple markers in Google Maps API v3 Resize Google Maps marker icon image How to create a custom-shaped bitmap marker with Android map API v2 Draw path between two points using Google Maps Android API v2 Google Maps API Multiple Markers with Infowindows Javascript, Change google map marker color How do you create a Marker with a custom icon for google maps API v3? Selecting last element in JavaScript array google maps v3 marker info window on mouseover