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

5

10

I have an array contains

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

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

Bautista answered 26/2, 2020 at 7:52 Comment(3)
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.Lumbard
To people answering with pop: Notice the "without modifying the source array" part of the question. :-) pop modifies the source array.Easter
Does this answer your question? Get the last item in an arrayIdioglossia
P
18

Using the function slice + destructuring assignment.

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

console.log(last);
Preclinical answered 26/2, 2020 at 7:58 Comment(2)
how is that different from my answer? even the destructuring is an overhead over a direct access with an index.Plan
Fancier, I think!Preclinical
P
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]);
Plan answered 26/2, 2020 at 7:54 Comment(0)
G
12

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));
Goldstein answered 23/2, 2022 at 18:8 Comment(2)
This, IMO, is the best solution because it gives the exact value of the last item in the array, not another array, and doesn't require a separate function.Mateya
I'm puzzled by why this is not more commonly found in code and suggested by refactoring tools and AI. Can anyone point out a drawback ore performance penalty to this? (apart from IE not getting the update)Precedent
E
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.

Easter answered 26/2, 2020 at 7:57 Comment(3)
@Preclinical - I should have put that in the answer, shouldn't I? :-) Done now.Easter
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.Finnie
@PeterSeliger - LOL, quite true. :-) Side note: last is now the subject of a proposal: github.com/tc39/proposal-array-lastEaster
L
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
Logomachy answered 17/8, 2023 at 9:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.