简体   繁体   中英

Get the last item in an array

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.

Not sure if there's a drawback, but this seems quite concise:

arr.slice(-1)[0] 

Use Array.pop<\/a> :

var lastItem = anArray.pop();

A shorter version of what @chaiguy posted:

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

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

http://jsperf.com/slice-vs-length-1-arr

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 

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.

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

I'd rather use array.pop()<\/code> than indexes.

while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));

I think if you only want get the element without remove, is more simple use this:

arr.slice(-1)[0]

Note: If the array is empty (eg. [] ) this will return undefined .

by the way... i didnt check performance, but i think is more simple and clean to write

const lastElement = myArray[myArray.length - 1];

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.

You can use relative indexing with Array#at<\/code><\/a> :

const myArray = [1, 2, 3]

console.log(myArray.at(-1))
// => 3

Getting the last item of an array can be achieved by using the slice<\/strong> method with negative values.

var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
  //your code...
}

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);

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.

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()<\/code> .

let thePop = arr.pop()
thePop && arr.push(thePop)

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.

ES6 object destructuring is another way to go.

You create another dynamic key using already extracted key by [length-1]<\/strong> and assign it to last<\/strong> , all in one line.

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 ];
    }
} );

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("."));

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]

jQuery solves this neatly:

> $([1,2,3]).get(-1)
3
> $([]).get(-1)
undefined

To prevent removing last item from origin array you could use

Array.from(myArray).pop()

Mostly supported of all browsers (ES6)

In ECMAScript proposal<\/a> Stage 1<\/a> there is a suggestion to add an array property that will return the last element: proposal-array-last<\/a> .

arr.lastItem // get last item
arr.lastItem = 'value' // set last item

arr.lastIndex // get last index

I think this should work fine.

var arr = [1, 2, 3];
var last_element = arr.reverse()[0];

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

Whatever you do don't just<\/em> use reverse()<\/code> !!!<\/h1>

A few answers mention reverse<\/code> but don't mention the fact that reverse<\/code> modifies the original array, and doesn't (as in some other language or frameworks) return a copy.

"

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]

You can add a last()<\/code> function to the Array<\/code> prototype.

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

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.

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.

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.

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.

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)));

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>

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])));
}

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>

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)

列出怪物

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 
}

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¡

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.

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])

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.

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'))

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' ] ] ]

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
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

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 

箭头函数通过不重复数组的名称,使执行最快的方法更加简洁。

var lastItem = (a => a[a.length - 1])(loc_array);

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);

使用reduceRight

[3,2,1,5].reduceRight((a,v) => a ? a : v);

使用新方法findLast<\/code>是另一种方法<\/strong>

 var arr = [1,2,3,4]; var last = arr.findLast(x => x); console.log(last); \/\/ 4<\/code><\/pre>

在此链接中<\/a>阅读有关findLast<\/code>更多信息

findLast<\/code>浏览器兼容性可以在这里<\/a>找到

"

ECMA 2022

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);

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.

simple answer

const array = [1,2,3]
array[array.length - 1]

Update 27 October 2021

You can now use Array.prototype.findLast :

const array = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
  { id: 3, name: 'Item 3' },
  { id: 4, name: 'Item 4' },
  { id: 5, name: 'Item 5' }
]

let last_element = array.findLast((item) => true);
// → { id: 5, name: 'Item 5' }

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
array.reverse()[0]

就这么简单

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM