How to find last element of an array without modifying source array in Vanilla Javascript

19.1k Views Asked by At

I have an array contains

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

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

5

There are 5 best solutions below

0
On

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

3
On

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.

2
On

Using the function slice + destructuring assignment.

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

console.log(last);

2
On

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

0
On

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