131

Is there a notation to access the last element of an array in TypeScript? In Ruby I can say: array[-1]. Is there something similar?

11 Answers 11

151

You can access the array elements by its index. The index for the last element in the array will be the length of the array-1 (as indexes are zero based).

This should work:

var items: String[] = ["tom", "jeff", "sam"];

alert(items[items.length-1])

Here is a working sample.

Sign up to request clarification or add additional context in comments.

4 Comments

That doesn't feel like a "notation" to me.
I agree with Amit. So far I haven't found a 'notation.' The next best which is a little more concise but still not a notation is items.slice(-1).
Not that I really care, but if you don't feel it's a good answer, why did you mark it as such?
@pitosalas slice returns an array ... as you have already discovered : stackoverflow.com/a/31277569/390330 :)
82

As of July 2021, browsers are starting to support the at() method for Arrays which allows for the following syntax:

const arr: number[] = [1, 2, 3];

// shows 3
alert(arr.at(-1)); 

It's not clear to me at what point TypeScript will start to support this (it's not working for me just yet) but it should be available soon I would guess.

Edit: This is available as of [email protected]

3 Comments

The .at method has the additional advantage of including undefined in the type should your index not be included in the array. typescriptlang.org/play?target=9&ts=4.6.2#code/…
This works for me. Defnitely my favorite option :)
61

If you don't need the array afterwards, you could use

array.pop()

But that removes the element from the array!

The pop returns T | undefined so you need to take care of that in your implementation.

If you are sure there will be always a value you can use non-null assertion operator (!):

     var poped = array.pop()
     array.push(poped!);

3 Comments

It may also give warning as Type 'undefined' is not assignable to type 'string'
Let's aim to not modify data structures if we don't have to. In general, we should strive for immutability, modifying structures just for the sake of access is ill-advised.
However, if using functional chaining, this feels the best way: ej const lastElem = myArray.map(...).filter(...).pop()
50

Here is another way which has not yet been mentioned:

items.slice(-1)[0]

2 Comments

Considering this creates an almost complete copy of the array I don't believe that's the best answer. If the array is quite large, this is not a good approach performancewise.
@Loop slice(-1) does not create a copy of all array. It'll copy just the last element into new array. I do believe this is a concise solution. Best solution for when this isn't called excessively as we create a throwaway array with one element each time just to get its element. Not too problematic but unnecessary in any case.
15

Here are a the options summarized together, for anyone finding this question late like me.

var myArray = [1,2,3,4,5,6];

// Fastest method, requires the array is in a variable
myArray[myArray.length - 1];

// Also very fast but it will remove the element from the array also, this may or may 
// not matter in your case.
myArray.pop();

// Slowest but very readable and doesn't require a variable
myArray.slice(-1)[0]

1 Comment

Is slice really much slower than the others? pop is also a function call.
9

If you need this call more often it's possible to declare it globally:

interface Array<T> {
    last(): T | undefined;
}
if (!Array.prototype.last) {
    Array.prototype.last = function () {
        if (!this.length) {
            return undefined;
        }
        return this[this.length - 1];
    };
}

then you can just call

items.last()

2 Comments

How do I declare it, globally?
Modifying the prototype of built-ins is not advisable.
7

One line Typescript function:

const last = <T>(arr: T[]): T | undefined => arr.at(-1);

if you use old ES versions:

function last<T>(arr: T[]): T | undefined {
    return arr[arr.length - 1];
}

All fns have almost the the same perfomance. I recommend you to use arr[arr.length - 1] as the most native.

enter image description here

Comments

6

I'm going with this one as my first contribution to stackoverflow:

var items: String[] = ["tom", "jeff", "sam"];

const lastOne = [...items].pop();

NOTE: Unlike the use of pop() without the spread operator, this approach doesn't remove the last element from the original array.

3 Comments

Oops! This is creating a whole new copy of the array. So the performance is almost quite terrible.
This was my first contribution to StackOverflow, I was young and naive .... Please, don't judge me!!! XD .... and please don't throw negatives at me! ;) (In later posts I think I offered better content). Cheers!
No worries, Juan. Don't take it personally. It's great to have all sorts of answers on StackOverflow, so people can see why some of them might not perform as fast as the others. At the end of the day, we all are here to learn and grow! Keep up the good work. :)
3

there are several ways you could do this.

  1. By the index of the last element.
arr[arr.length - 1]
  1. Use the slice function: this function returns the value in an array that's why accessing the 0'th index is required.
arr.slice(-1)[0]
  1. Use the pop() function: this method is helpful when you need to get and remove the last element of the array. element will be returned and the last element will be removed from the original array.
arr.pop()
  1. Use the at() function. NOTE: This was introduced in ES22 and will not work in older versions
arr.at(-1)

You can pick any one of those methods based on your preferences.

Comments

1

const arr = [1, 3, 6, 2];
console.log(...arr.slice(-1)); // 2

2 Comments

Is using the spread a good idea here? We only want a single element.
Note: the spread operator will only work in this case if you need to use the last value to pass directly into a function, as the spread operator maps the positions of the array to the parameters of the functions in order
1
let arry = [A, B, C, D, E, F];
let [lastElement] = arry.slice(-1);

console.log(lastElement);

You will get the Answer as F .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.