9

I have an array contains

const data = ['a', 'b', 'c', 'd'];

how to find the last element, result should be 'd'

Debug Diva
  • 26,058
  • 13
  • 70
  • 123
Syam Prasad
  • 149
  • 1
  • 1
  • 6
  • 1
    Your question is asking how too **find** the last element without modifying and you answer your own question in the question itself. Maybe rephrase your question so that it complements the description you wrote. – Kerwin Sneijders Feb 26 '20 at 07:58
  • 6
    **To people answering with `pop`:** Notice the *"without modifying the source array"* part of the question. :-) `pop` modifies the source array. – T.J. Crowder Feb 26 '20 at 08:00
  • 1
    Does this answer your question? [Get the last item in an array](https://stackoverflow.com/questions/3216013/get-the-last-item-in-an-array) – Fede Garcia Feb 04 '21 at 19:11

5 Answers5

18

Using the function slice + destructuring assignment.

const data = ['a', 'b', 'c', 'd'],
      [last] = data.slice(-1);

console.log(last);
Ele
  • 33,468
  • 7
  • 37
  • 75
12

You could slice from the end (negative index) and get the item of the array.

const data = ['a', 'b', 'c', 'd'];

console.log(data.slice(-1)[0]);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
9

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 data = ['a', 'b', 'c', 'd'];

console.log(data.at(-1));
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
7

Back in the day, the PrototypeJS library added methods to arrays like first and last. So if you want an alternative to data[data.length - 1], you could have a utility method in your standard toolkit:

Object.defineProperty(Array.prototype, "last", {
    value() {
        return this[this.length - 1];
    },
    enumerable: false, // (This is the default, you can leave it off if you like)
    writable: true,
    configurable: true
});

and then use that:

console.log(data.last()); // 'd'

There's an active proposal to add this to JavaScript as well.

Live Example:

// In the toolkit
Object.defineProperty(Array.prototype, "last", {
    value() {
        return this[this.length - 1];
    },
    writable: true,
    configurable: true
});

// Using it:

const data = ['a', 'b', 'c', 'd'];
console.log(data.last());

It's important to use defineProperty to create any property you add to Array.prototype (or heaven forfend, Object.prototype) leaving off the enumerable flag (or setting it false, which is the default) so that what you're adding is non-enumerable (doesn't show up in for-in loops). (You usually shouldn't use for-in to loop through arrays — do one of these things instead — but...people do.) If you just did Array.prototype.last = function() { /*...*/ };, last would be enumerable.

Just be sure only to do this in your own app/page code, not code you write and distribute as a library. Modifying built-in prototypes (other than polyfilling), even using defineProperty, is usually a bad idea in libraries other people will use.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @Ele - I should have put that in the answer, shouldn't I? :-) Done now. – T.J. Crowder Feb 26 '20 at 08:04
  • 1
    Using (almost) the same approach one even could write ... `Object.defineProperty(Array.prototype, '-1', { get() { return this.slice(-1)[0]; } });` ... and then access any array's last item like ... `[9, 8, 7, 6, 5][-1]` ... which for the latter example does return `5`. – Peter Seliger Oct 19 '20 at 11:11
  • @PeterSeliger - LOL, quite true. :-) Side note: `last` is now the subject of a proposal: https://github.com/tc39/proposal-array-last – T.J. Crowder Oct 19 '20 at 12:35
0

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 = ['a', 'b', 'c', 'd'];

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:

//d
//using array length: 0.200ms
//d
//using slice method: 0.175ms
//d
//using pop method: 0.012ms