How to Get the Last Element of an Array in TypeScript?

One of my team members recently asked about getting the last element of an array in TypeScript. I suggested a few methods. In this tutorial, I will explain how to get the last element of an array in TypeScript with some real examples.

Get the Last Element of an Array in TypeScript

Arrays in TypeScript allow you to store collections of elements. Often, you may need to access the last element of an array. Let me show you various methods to achieve this in TypeScript.

Using the Length Property

The most used way to get the last element of an array is by using the length property. Since array indices are zero-based, the index of the last element is array.length - 1.

Example

let customers: string[] = ["John Doe", "Jane Smith", "Alice Johnson", "Michael Brown"];
let lastCustomer: string = customers[customers.length - 1];
console.log(lastCustomer); // Output: Michael Brown

In this example, we have an array of customer names. By accessing customers[customers.length - 1], we retrieve the last customer, “Michael Brown”.

Here is the exact output in the screenshot below:

Get the Last Element of an Array in TypeScript

Check out Get the First Element of an Array in TypeScript

Using the Array at() Method

TypeScript also supports the at() method, which allows you to access elements using negative indices. This method is particularly useful for accessing the last element directly.

Example

let customers: string[] = ["John Doe", "Jane Smith", "Alice Johnson", "Michael Brown"];
let lastCustomer: string = customers.at(-1)!;
console.log(lastCustomer); // Output: Michael Brown

The at() method with -1 as an argument returns the last element of the array. The exclamation mark (!) is used to assert that the result is not null or undefined.

Here is the exact output in the screenshot below:

How to Get the Last Element of an Array in TypeScript

Check out Check if an Array is Null or Empty in TypeScript

Using Array Destructuring with slice()

Another elegant way to get the last element of an array is by using array destructuring in combination with the slice() method.

Example

let customers: string[] = ["John Doe", "Jane Smith", "Alice Johnson", "Michael Brown"];
let [lastCustomer]: string[] = customers.slice(-1);
console.log(lastCustomer); // Output: Michael Brown

In this example, customers.slice(-1) returns a new array containing the last element, which is then destructured into the lastCustomer variable.

Using Lodash Library

For those who prefer using utility libraries, Lodash provides a convenient _.last() function to get the last element of an array.

Example

First, you need to install Lodash:

npm install lodash

Then, you can use it as follows:

import _ from 'lodash';

let customers: string[] = ["John Doe", "Jane Smith", "Alice Johnson", "Michael Brown"];
let lastCustomer: string = _.last(customers)!;
console.log(lastCustomer); // Output: Michael Brown

Lodash’s _.last() function simplifies the process, providing a clean and readable way to access the last element.

Read Remove Empty Strings from an Array in TypeScript

Practical Examples

Now, let me show you two real examples where we can get the last element from a TypeScript array.

Processing Recent Data Entries

In many applications, especially those involving real-time data, you might need to process the most recent entry in an array. For instance, consider a scenario where you are monitoring customer service requests:

let serviceRequests: { id: number, customer: string, issue: string }[] = [
  { id: 101, customer: "John Doe", issue: "Login issue" },
  { id: 102, customer: "Jane Smith", issue: "Payment failure" },
  { id: 103, customer: "Alice Johnson", issue: "Account locked" },
  { id: 104, customer: "Michael Brown", issue: "Password reset" }
];

let latestRequest = serviceRequests[serviceRequests.length - 1];
console.log(latestRequest); // Output: { id: 104, customer: "Michael Brown", issue: "Password reset" }

Here, accessing the last element allows you to quickly respond to the most recent customer issue.

Handling Paginated Data

When dealing with paginated data, such as fetching results from an API, you might need to keep track of the last fetched item to request the next set of data:

let fetchedData: number[] = [1, 2, 3, 4, 5];
let lastFetchedItem: number = fetchedData[fetchedData.length - 1];
console.log(lastFetchedItem); // Output: 5

// Use lastFetchedItem to fetch the next set of data

In this case, knowing the last fetched item helps in maintaining the continuity of data retrieval.

Conclusion

In this tutorial, I explained how to access the last element of an array in TypeScript using different ways, such as using the length property, the at() method, array destructuring, or utility libraries like Lodash, etc.

You may also like: