Get the last item in an array
JavascriptArraysEs2022Javascript Problem Overview
Here is my JavaScript code so far:
var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
linkElement.appendChild(newT);
Currently it takes the second to last item in the array from the URL. However, I want to do a check for the last item in the array to be "index.html"
and if so, grab the third to last item instead.
Javascript Solutions
Solution 1 - Javascript
if (loc_array[loc_array.length - 1] === 'index.html') {
// do something
} else {
// something else
}
In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase()
.
Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.
EDIT - ES-2022
Using ES-2022 Array.at()
, the above may be written like this:
if (loc_array.at(-1) === 'index.html') {
// do something
} else {
// something else
}
Solution 2 - Javascript
Not sure if there's a drawback, but this seems quite concise:
arr.slice(-1)[0]
or
arr.slice(-1).pop()
Both will return undefined
if the array is empty.
Solution 3 - Javascript
Use [Array.pop][1]:
var lastItem = anArray.pop();
Important : This returns the last element and removes it from the array [1]: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/pop
Solution 4 - Javascript
A shorter version of what @chaiguy posted:
Array.prototype.last = function() {
return this[this.length - 1];
}
Reading the -1 index returns undefined
already.
EDIT:
These days the preference seems to be using modules and to avoid touching the prototype or using a global namespace.
export function last(array) {
return array[array.length - 1];
}
Solution 5 - Javascript
Two options are:
var last = arr[arr.length - 1]
or
var last = arr.slice(-1)[0]
The former is faster, but the latter looks nicer
Solution 6 - Javascript
Performance
Today 2020.05.16 I perform tests of chosen solutions on Chrome v81.0, Safari v13.1 and Firefox v76.0 on MacOs High Sierra v10.13.6
Conclusions
arr[arr.length-1]
(D) is recommended as fastest cross-browser solution- mutable solution
arr.pop()
(A) and immutable_.last(arr)
(L) are fast - solutions I, J are slow for long strings
- solutions H, K (jQuery) are slowest on all browsers
Details
I test two cases for solutions:
for two cases
- short string - 10 characters - you can run test HERE
- long string - 1M characters - you can run test HERE
function A(arr) {
return arr.pop();
}
function B(arr) {
return arr.splice(-1,1);
}
function C(arr) {
return arr.reverse()[0]
}
function D(arr) {
return arr[arr.length - 1];
}
function E(arr) {
return arr.slice(-1)[0] ;
}
function F(arr) {
let [last] = arr.slice(-1);
return last;
}
function G(arr) {
return arr.slice(-1).pop();
}
function H(arr) {
return [...arr].pop();
}
function I(arr) {
return arr.reduceRight(a => a);
}
function J(arr) {
return arr.find((e,i,a)=> a.length==i+1);
}
function K(arr) {
return $(arr).get(-1);
}
function L(arr) {
return _.last(arr);
}
function M(arr) {
return _.nth(arr, -1);
}
// ----------
// TEST
// ----------
let loc_array=["domain","a","b","c","d","e","f","g","h","file"];
log = (f)=> console.log(`${f.name}: ${f([...loc_array])}`);
[A,B,C,D,E,F,G,H,I,J,K,L,M].forEach(f=> log(f));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>
Example results for Chrome for short string
Solution 7 - Javascript
Here's how to get it with no effect on the original ARRAY
a = [1,2,5,6,1,874,98,"abc"];
a.length; //returns 8 elements
If you use pop(), it will modify your array
a.pop(); // will return "abc" AND REMOVES IT from the array
a.length; // returns 7
But you can use this so it has no effect on the original array:
a.slice(-1).pop(); // will return "abc" won't do modify the array
// because slice creates a new array object
a.length; // returns 8; no modification and you've got you last element
Solution 8 - Javascript
The "cleanest" ES6 way (IMO) would be:
const foo = [1,2,3,4];
const bar = [...foo].pop();
This avoids mutating foo
, as .pop()
would had, if we didn't used the spread operator.
That said, I like aswell the foo.slice(-1)[0]
solution.
Solution 9 - Javascript
const [y] = x.slice(-1)
> Quick Explanation:
>
> This syntax [y] = <array/object>
is called destructuring assignment & according to Mozilla docs, the destructuring assingment makes possible to unpack values from an array or properties from an object into distinct variables
>
> Read more about it: here
Solution 10 - Javascript
const [lastItem] = array.slice(-1);
Array.prototype.slice with -1 can be used to create a new Array containing only the last item of the original Array, you can then use Destructuring Assignment to create a variable using the first item of that new Array.
const lotteryNumbers = [12, 16, 4, 33, 41, 22]; const [lastNumber] = lotteryNumbers.slice(-1);
console.log(lotteryNumbers.slice(-1)); // => [22] console.log(lastNumber); // => 22
Solution 11 - Javascript
I'd rather use array.pop()
than indexes.
while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));
this way you always get the element previous to index.html (providing your array has isolated index.html as one item). Note: You'll lose the last elements from the array, though.
Solution 12 - Javascript
You can use relative indexing with Array#at
:
const myArray = [1, 2, 3]
console.log(myArray.at(-1))
// => 3
Solution 13 - Javascript
const lastElement = myArray[myArray.length - 1];
This is the best options from performance point of view (~1000 times faster than arr.slice(-1)
).
Solution 14 - Javascript
You can use this pattern...
let [last] = arr.slice(-1);
While it reads rather nicely, keep in mind it creates a new array so it's less efficient than other solutions but it'll almost never be the performance bottleneck of your application.
Solution 15 - Javascript
If one wants to get the last element in one go, he/she may use Array#splice()
:
lastElement = document.location.href.split('/').splice(-1,1);
Here, there is no need to store the split elements in an array, and then get to the last element. If getting last element is the only objective, this should be used.
Note: This changes the original array by removing its last element. Think of splice(-1,1)
as a pop()
function that pops the last element.
Solution 16 - Javascript
Multiple ways to find last value of an array in javascript
- Without affecting original array
var arr = [1,2,3,4,5];
console.log(arr.slice(-1)[0])
console.log(arr[arr.length-1])
const [last] = [...arr].reverse();
console.log(last)
let copyArr = [...arr];
console.log(copyArr.reverse()[0]);
- Modifies original array
var arr = [1,2,3,4,5];
console.log(arr.pop())
arr.push(5)
console.log(...arr.splice(-1));
- By creating own helper method
let arr = [1, 2, 3, 4, 5];
Object.defineProperty(arr, 'last',
{ get: function(){
return this[this.length-1];
}
})
console.log(arr.last);
Solution 17 - Javascript
Getting the last item of an array can be achieved by using the slice method with negative values.
You can read more about it here at the bottom.
var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
//your code...
}
Using pop() will change your array, which is not always a good idea.
Solution 18 - Javascript
This question has been around a long time, so I'm surprised that no one mentioned just putting the last element back on after a pop()
.
arr.pop()
is exactly as efficient as arr[arr.length-1]
, and both are the same speed as arr.push()
.
Therefore, you can get away with:
---EDITED [check that thePop
isn't undefined
before pushing]---
let thePop = arr.pop()
thePop && arr.push(thePop)
---END EDIT---
Which can be reduced to this (same speed [EDIT: but unsafe!]):
arr.push(thePop = arr.pop()) //Unsafe if arr empty
This is twice as slow as arr[arr.length-1]
, but you don't have to stuff around with an index. That's worth gold on any day.
arr[arr.length-1]
:
[Method]..............[ETUs 5 elems]...[ETU 1 million elems]
Of the solutions I've tried, and in multiples of the Execution Time Unit (ETU) of arr[arr.length - 1] ------> 1 -----> 1
let myPop = arr.pop()
arr.push(myPop) ------> 2 -----> 2
arr.slice(-1).pop() ------> 36 -----> 924
arr.slice(-1)[0] ------> 36 -----> 924
[...arr].pop() ------> 120 -----> ~21,000,000 :)
The last three options, ESPECIALLY [...arr].pop()
, get VERY much worse as the size of the array increases. On a machine without the memory limitations of my machine, [...arr].pop()
probably maintains something like it's 120:1 ratio. Still, no one likes a resource hog.
Solution 19 - Javascript
Just putting another option here.
loc_array.splice(-1)[0] === 'index.html'
I found the above approach more clean and short onliner. Please, free feel to try this one.
Note: It will modify the original array, if you don't want to modify it you can use slice()
loc_array.slice(-1)[0] === 'index.html'
Thanks @VinayPai for pointing this out.
Solution 20 - Javascript
ES6 object destructuring is another way to go.
const {length, [length-1]: last}=[1,2,3,4,5]
console.log(last)
You extract length property from Array using object destructuring. You create another dynamic key using already extracted key by [length-1] and assign it to last, all in one line.
Solution 21 - Javascript
For those not afraid to overload the Array prototype (and with enumeration masking you shouldn't be):
Object.defineProperty( Array.prototype, "getLast", {
enumerable: false,
configurable: false,
writable: false,
value: function() {
return this[ this.length - 1 ];
}
} );
Solution 22 - Javascript
Here's more Javascript art if you came here looking for it
In the spirit of another answer that used reduceRight()
, but shorter:
[3, 2, 1, 5].reduceRight(a => a);
It relies on the fact that, in case you don't provide an initial value, the very last element is selected as the initial one (check the docs here). Since the callback just keeps returning the initial value, the last element will be the one being returned in the end.
Beware that this should be considered Javascript art and is by no means the way I would recommend doing it, mostly because it runs in O(n) time, but also because it hurts readability.
And now for the serious answer
The best way I see (considering you want it more concise than array[array.length - 1]
) is this:
const last = a => a[a.length - 1];
Then just use the function:
last([3, 2, 1, 5])
The function is actually useful in case you're dealing with an anonymous array like [3, 2, 1, 5]
used above, otherwise you'd have to instantiate it twice, which would be inefficient and ugly:
[3, 2, 1, 5][[3, 2, 1, 5].length - 1]
Ugh.
For instance, here's a situation where you have an anonymous array and you'd have to define a variable, but you can use last()
instead:
last("1.2.3".split("."));
Solution 23 - Javascript
I generally use underscorejs, with it you can just do
if (_.last(loc_array) === 'index.html'){
etc...
}
For me that is more semantic than loc_array.slice(-1)[0]
Solution 24 - Javascript
jQuery solves this neatly:
> $([1,2,3]).get(-1)
3
> $([]).get(-1)
undefined
Solution 25 - Javascript
Getting the last item is possible via the length
property. Since the array count starts at 0, you can pick the last item by referencing the array.length - 1
item
const arr = [1,2,3,4];
const last = arr[arr.length - 1];
console.log(last); // 4
Another option is using the new Array.prototype.at()
method which takes an integer value and returns the item at that index. Negative integers count back from the last item in the array so if we want the last item we can just pass in -1
const arr = [1,2,3,4];
const last = arr.at(-1);
console.log(last); // 4
Another option is using the new findLast
method. You can see the proposal here
const arr = [1,2,3,4];
const last = arr.findLast(x => true);
console.log(last); // 4
Solution 26 - Javascript
To prevent removing last item from origin array you could use
Array.from(myArray).pop()
Mostly supported of all browsers (ES6)
Solution 27 - Javascript
In ECMAScript proposal Stage 1 there is a suggestion to add an array property that will return the last element: proposal-array-last.
Syntax:
arr.lastItem // get last item
arr.lastItem = 'value' // set last item
arr.lastIndex // get last index
You can use polyfill.
Proposal author: Keith Cirkel(chai autor)
Solution 28 - Javascript
I think this should work fine.
var arr = [1, 2, 3];
var last_element = arr.reverse()[0];
Just reverse the array and get the first element.
Edit: As mentioned below, the original array will be reversed. To avoid that you can change the code to:
var arr = [1, 2, 3];
var last_element = arr.slice().reverse()[0];
This will create a copy of the original array.
Solution 29 - Javascript
reverse()
!!!
Whatever you do don't just use A few answers mention reverse
but don't mention the fact that reverse
modifies the original array, and doesn't (as in some other language or frameworks) return a copy.
var animals = ['dog', 'cat'];
animals.reverse()[0]
"cat"
animals.reverse()[0]
"dog"
animals.reverse()[1]
"dog"
animals.reverse()[1]
"cat"
This can be the worst type of code to debug!
Solution 30 - Javascript
Personally I would upvote answer by kuporific / kritzikratzi. The array[array.length-1] method gets very ugly if you're working with nested arrays.
var array = [[1,2,3], [4,5,6], [7,8,9]]
array.slice(-1)[0]
//instead of
array[array.length-1]
//Much easier to read with nested arrays
array.slice(-1)[0].slice(-1)[0]
//instead of
array[array.length-1][array[array.length-1].length-1]
Solution 31 - Javascript
You can add a last()
function to the Array
prototype.
Array.prototype.last = function () {
return this[this.length - 1];
};
EDIT:
You can use a Symbol
to avoid incompatibility with other code:
const last = Symbol('last');
Array.prototype[last] = function() {
return this[this.length - 1];
};
console.log([0, 1][last]());
Solution 32 - Javascript
You could add a new property getter to the prototype of Array
so that it is accessible through all instances of Array
.
Getters allow you to access the return value of a function just as if it were the value of a property. The return value of the function of course is the last value of the array (this[this.length - 1]
).
Finally you wrap it in a condition that checks whether the last
-property is still undefined
(not defined by another script that might rely on it).
Object.defineProperty(Array.prototype, 'last', {
get : function() {
return this[this.length - 1];
}
});
// Now you can access it like
[1, 2, 3].last; // => 3
// or
var test = [50, 1000];
alert(test.last); // Says '1000'
Solution 33 - Javascript
EDITED:
Recently I came up with one more solution which I now think is the best for my needs:
function w(anArray) {
return {
last() {
return anArray [anArray.length - 1];
};
};
}
With the above definition in effect I can now say:
let last = w ([1,2,3]).last();
console.log(last) ; // -> 3
The name "w" stands for "wrapper". You can see how you could easily add more methods besides 'last()' to this wrapper.
I say "best for my needs", because this allows me to easily add other such "helper methods" to any JavaScript built-in type. What comes to mind are the car() and cdr() of Lisp for instance.
Solution 34 - Javascript
I think the easiest to understand for beginners and super inefficient way is:
var array = ['fenerbahce','arsenal','milan'];
var reversed_array = array.reverse(); //inverts array [milan,arsenal,fenerbahce]
console.log(reversed_array[0]) // result is "milan".
Solution 35 - Javascript
I'll suggest to create helper function and reuse it every time, you'll need it. Lets make function more general to be able to get not only last item, but also second from the last and so on.
function last(arr, i) {
var i = i || 0;
return arr[arr.length - (1 + i)];
}
Usage is simple
var arr = [1,2,3,4,5];
last(arr); //5
last(arr, 1); //4
last(arr, 9); //undefined
Now, lets solve the original issue
>Grab second to last item form array. If the last item in the loc_array is "index.html" grab the third to last item instead.
Next line does the job
last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);
So, you'll need to rewrite
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
in this way
var newT = document.createTextNode(unescape(capWords(last(loc_array, last(loc_array) === 'index.html' ? 2 : 1))));
or use additional variable to increase readability
var nodeName = last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);
var newT = document.createTextNode(unescape(capWords(nodeName)));
Solution 36 - Javascript
Functional programming with Ramda
If you're using JS, I would suggest checking out Ramda which is a functional-programming library (like Lodash and Underscore, except more advanced and modular). Ramda provides this with R.last
import * as R from 'ramda';
R.last(['fi', 'fo', 'fum']); //=> 'fum'
R.last([]); //=> undefined
R.last('abc'); //=> 'c'
R.last(''); //=> ''
It further provides init
, head
, tail
. List monster from (Learn You a Haskell)
Solution 37 - Javascript
Normally you are not supposed to mess with the prototype of built-in types but here is a hack/shortcut:
Object.defineProperty(Array.prototype, 'last', {
get() {
return this[this.length - 1];
}
});
This will allow all array objects to have a last
property, which you can use like so:
const letters = ['a', 'b', 'c', 'd', 'e'];
console.log(letters.last); // 'e'
You are not supposed to mess with a built-in type's prototype because you never when a new ES version will be released and in the event that a new version uses the same property name as your custom property, all sorts of breaks can happen. Also, it makes it hard for others to follow your code, especially for people joining the team. You COULD make the property to something that you know an ES version would never use, like listLastItem
but that is at the discretion of the developer.
Or you can use a simple method:
const getLast = (list) => list[list.length - 1];
const last = getLast([1,2,3]); // returns 3
Solution 38 - Javascript
As per ES2022, You can use Array.at() method which takes an integer value and returns the item at that index. Allowing for positive and negative integers. Negative integers count back from the last item in the array.
Demo :
const href = 'www.abc.com/main/index.html';
const loc_array = href.split('/');
// To access elements from an array we can use Array.at()
console.log(loc_array.at(-1)); // This will return item at last index.
Solution 39 - Javascript
Using ES6/ES2015 spread operator (...) you can do the following way.
const data = [1, 2, 3, 4]
const [last] = [...data].reverse()
console.log(last)
Please notice that using spread operator and reverse we did not mutated original array, this is a pure way of getting a last element of the array.
Solution 40 - Javascript
Using lodash _.last(array) Gets the last element of array.
data = [1,2,3]
last = _.last(data)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Solution 41 - Javascript
How about something like below:
if ('index.html' === array[array.length - 1]) {
//do this
} else {
//do that
}
If using Underscore or Lodash, you can use _.last()
, so something like:
if ('index.html' === _.last(array)) {
//do this
} else {
//do that
}
Or you can create your own last function:
const _last = arr => arr[arr.length - 1];
and use it like:
if ('index.html' === _last(array)) {
//do this
} else {
//do that
}
Solution 42 - Javascript
Will this work?
if (loc_array.pop() == "index.html"){
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-3])));
}
else{
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
}
Solution 43 - Javascript
This can be done with lodash _.last
or _.nth
:
var data = [1, 2, 3, 4]
var last = _.nth(data, -1)
console.log(last)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Solution 44 - Javascript
Update - 27 October 2021 (Chrome 97+)
Proposal for Array.prototype.findLast
is now on Stage 3!
Here's how you can use it:
const array = [1, 2, 3, 4, 5];
const last_element = array.findLast((item) => true);
console.log(last_element);
You can read more in this V8 blog post.
You can find more in "New in Chrome" series.
Solution 45 - Javascript
You can achieve this issue also without extracting an array from the url
This is my alternative
var hasIndex = (document.location.href.search('index.html') === -1) ? doSomething() : doSomethingElse();
!Greetings¡
Solution 46 - Javascript
This is clean and efficient:
let list = [ 'a', 'b', 'c' ]
(xs => xs[xs.length - 1])(list)
If you install a pipe operator using Babel it becomes:
list |> (xs => xs[xs.length - 1])
Solution 47 - Javascript
Another ES6
only option would be to use Array.find(item, index)=> {...})
as follows:
const arr = [1, 2, 3];
const last = arr.find((item, index) => index === arr.length - 1);
little practical value, posted to show that index is also available for your filtering logic.
Solution 48 - Javascript
This method will not mess with your prototype. It also guards against 0
length arrays, along with null
/undefined
arrays. You can even override the default value if the returned default value might match an item in your array.
const items = [1,2,3]
const noItems = []
/**
* Returns the last item in an array.
* If the array is null, undefined, or empty, the default value is returned.
*/
function arrayLast (arrayOrNull, defVal = undefined) {
if (!arrayOrNull || arrayOrNull.length === 0) {
return defVal
}
return arrayOrNull[arrayOrNull.length - 1]
}
console.log(arrayLast(items))
console.log(arrayLast(noItems))
console.log(arrayLast(null))
console.log(arrayLast(items, 'someDefault'))
console.log(arrayLast(noItems, 'someDefault'))
console.log(arrayLast(null, 'someDefault'))
Solution 49 - Javascript
Update 2020
Array.prototype.last = function(){
return this[this.length - 1];
}
let a = [1, 2, 3, [4, 5]];
console.log(a.last());
// [ 4, 5 ]
console.log(a.last().last());
// 5
Setter and Getter
Array.prototype.last = function(val=null) {
if (this.length === 0) {
if (val) this[0] = val;
else return null;
}
temp = this;
while(typeof temp[temp.length-1] === "object") {
temp = temp[temp.length-1];
}
if (val) temp[temp.length-1] = val; //Setter
else return temp[temp.length-1]; //Getter
}
var arr = [[1, 2], [2, 3], [['a', 'b'], ['c', 'd']]];
console.log(arr.last()); // 'd'
arr.last("dd");
console.log(arr); // [ [ 1, 2 ], [ 2, 3 ], [ [ 'a', 'b' ], [ 'c', 'dd' ] ] ]
Solution 50 - Javascript
The arrow function makes the fastest-performing method more concise, by not repeating the name of the array.
var lastItem = (a => a[a.length - 1])(loc_array);
Solution 51 - Javascript
var str = ["stackoverflow", "starlink"];
var last = str[str.length-1];//basically you are putting the last index value into the array and storing it in la
Solution 52 - Javascript
There is also a npm module, that add last
to Array.prototype
npm install array-prototype-last --save
usage
require('array-prototype-last');
[1, 2, 3].last; //=> 3
[].last; //=> undefined
Solution 53 - Javascript
For a readable and concise solution, you can use a combination of Array.prototype.slice
and destructuring.
const linkElement = document.getElementById("BackButton");
const loc_array = document.location.href.split('/');
// assign the last three items of the array to separate variables
const [thirdLast, secondLast, last] = loc_array.slice(-3);
// use the second last item as the slug...
let parentSlug = secondLast;
if (last === 'index.html') {
// ...unless this is an index
parentSlug = thirdLast;
}
const newT = document.createTextNode(
unescape(
capWords(parentSlug)
)
);
linkElement.appendChild(newT);
But to simply get the last item in an array, I prefer this notation:
const [lastItem] = loc_array.slice(-1);
Solution 54 - Javascript
To Find the last Element in an array, use the following:
let arr = [1,2,3,4,5];
1) console.log(arr[arr.length-1])
2) console.log(arr.slice(-1)[0])
3) console.log(arr.findLast(x => true))
4) console.log(arr.at(-1))
many more...
~ Rahul Daksh
Solution 55 - Javascript
Using reduceRight:
[3,2,1,5].reduceRight((a,v) => a ? a : v);
Solution 56 - Javascript
simple answer
const array = [1,2,3]
array[array.length - 1]
Solution 57 - Javascript
The simple way to get last item of array:
var last_item = loc_array.reverse()[0];
Of course, we need to check to make sure array has at least one item first.
Solution 58 - Javascript
to access the last element in array using c# we can use GetUpperBound(0)
(0) in case if this one dimention array
my_array[my_array.GetUpperBound(0)] //this is the last element in this one dim array
Solution 59 - Javascript
array.reverse()[0]
That's so simple