Reputation: 24349
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.
Upvotes: 2152
Views: 3550973
Reputation: 1935
I'm using .at()
most of the time:
let arr = [1, 2, 3, 4, 5];
let lastElement = arr.at(-1);
console.log(lastElement);
Upvotes: 6
Reputation: 18026
Retrieving the last item in an array 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 (currently in stage 4)
const arr = [1,2,3,4];
const last = arr.findLast(x => true);
console.log(last); // 4
Another option is using the Array.prototype.slice()
method which simply returns a shallow copy of a portion of an array into a new array object.
const arr = [1,2,3,4];
const last = arr.slice(-1)[0];
console.log(last); // 4
Upvotes: 116
Reputation: 1356
Update: Since 2022:
const y = x.at(-1)
You can still use, but you decide:
const y = x[x.length - 1]
Upvotes: 67
Reputation: 1001
You can use snippet that extends the functionality of arrays by adding a new method called last(). This method can be used various approach to retrieve the last item of an array. Choose one of the many possibilities:
Array.prototype.last = function() {
return this[this.length - 1]
// return this.slice(-1)[0]
// return this.at(-1)
// return this.findLast(x => true)
// return [...this].reverse()[0]
// return this.reduceRight(_ => _)
// return this.slice().reverse()[0]
// return this.pop()
// return this.splice(-1,1)[0]
// return [...this].pop()
// return this.find((_,i,a)=>a.length==i+1)
}
console.log([2,4,6].last()) // 6
console.log([1, 2, 3].last()) // 3
Upvotes: 0
Reputation: 1461
In case your indices are random strings, уоu can use this:
arr[Object.keys(arr)[Object.keys(arr).length - 1]]
Upvotes: 0
Reputation: 144
The pop() and slice() both method are faster. You can use pop() method if you are fine with modifying the array. If you don't want to change the array, the slice() method can be used.
let arrItems = [12, 24, 60, 80, 10, 14, 123];
console.time('using array length');
let lastItem = arrItems[arrItems.length - 1];
console.log(lastItem);
console.timeEnd('using array length');
console.time('using slice method');
let lastItem1 = arrItems.slice(-1)[0];
console.log(lastItem1);
console.timeEnd('using slice method');
console.time('using pop method');
let lastItem2 = arrItems.pop();
console.log(lastItem2);
console.timeEnd('using pop method');
//Output:
//123
//using array length: 0.200ms
//123
//using slice method: 0.175ms
//123
//using pop method: 0.012ms
Upvotes: 0
Reputation: 1
The
findLastIndex()
method iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
const arr = [1,2,3,4];
const lastIndex = arr.findLastIndex(x => true);
console.log(arr[lastIndex]); // 4
PS: findLastIndex()
method is supported by all browsers and on Node.js version 18+.
see browser compatibility
Upvotes: 1
Reputation: 17566
With ECMA 2022 you have a new property at()
. To get the last element from a Array or a string you can use at
with the negative index -1
. [1,2,3].at(-1)
. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
If you like more fluent like arr.last to receive the last item you can define your own property to the array object.
if (!Array.prototype.hasOwnProperty("last")) {
Object.defineProperty(Array.prototype, "last", {
get() {
return this.at(-1);
}
});
}
a = [1,2,3];
console.log(a.last);
Upvotes: 19
Reputation: 34347
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
}
Upvotes: 2537
Reputation: 20304
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.
Upvotes: 6
Reputation: 27192
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.
Upvotes: 11
Reputation: 4064
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'
Upvotes: 9
Reputation: 2038
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
Upvotes: 6
Reputation: 9172
You can use relative indexing with Array#at
:
const myArray = [1, 2, 3]
console.log(myArray.at(-1))
// => 3
Upvotes: 47
Reputation: 2109
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]());
Upvotes: 10
Reputation: 1884
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".
Upvotes: 7
Reputation: 47
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
Upvotes: 2
Reputation: 346
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.
Upvotes: 13
Reputation: 3111
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
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' ] ] ]
Upvotes: 3
Reputation: 9769
Multiple ways to find last value of an array in javascript
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]);
var arr = [1,2,3,4,5];
console.log(arr.pop())
arr.push(5)
console.log(...arr.splice(-1));
let arr = [1, 2, 3, 4, 5];
Object.defineProperty(arr, 'last',
{ get: function(){
return this[this.length-1];
}
})
console.log(arr.last);
Upvotes: 31
Reputation: 2426
const lastElement = myArray[myArray.length - 1];
This is the best options from performance point of view (~1000 times faster than arr.slice(-1)
).
Upvotes: 39
Reputation: 92377
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
arr[arr.length-1]
(D) is recommended as fastest cross-browser solutionarr.pop()
(A) and immutable _.last(arr)
(L) are fastI test two cases for solutions:
for two cases
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
Upvotes: 159
Reputation: 1292
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.
Upvotes: 22
Reputation: 2359
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);
Upvotes: 1
Reputation: 479
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.
Upvotes: 24
Reputation: 20756
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.
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("."));
Upvotes: 22
Reputation: 17
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
Upvotes: -4
Reputation: 4196
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
Upvotes: 56
Reputation: 145950
reverse()
!!!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!
Upvotes: 13