How to Reverse an Array in TypeScript?

As a TypeScript developer, you might get requirements to reverse an array. There are various methods to do this. In this tutorial, I will explain how to reverse an array in TypeScript with some examples.

Reverse an Array in TypeScript

Let me show you how to reverse an array in TypeScript using different methods and examples.

Using reverse() Method

TypeScript, like JavaScript, provides a built-in method called reverse() that reverses the elements of an array in place. This method modifies the original array and returns the reference to the same array.

Example:

let cities: string[] = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];
cities.reverse();
console.log(cities); // Output: ["Phoenix", "Houston", "Chicago", "Los Angeles", "New York"]

In this example, the reverse() method is used to reverse the array of city names. The original array is modified, and the elements are reversed in place.

Here is the exact output in the screenshot below:

Reverse an Array in TypeScript

Check out Clear an Array in TypeScript While Preserving Its Type

Create a New Reversed Array Without Modifying the Original

Sometimes, you might want to reverse an array without modifying the original array. In such cases, you can use the slice() method to create a copy of the array and then apply the reverse() method.

Example:

let cities: string[] = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];
let reversedCities: string[] = cities.slice().reverse();
console.log(reversedCities); // Output: ["Phoenix", "Houston", "Chicago", "Los Angeles", "New York"]
console.log(cities); // Output: ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]

Here, the slice() method is used to create a shallow copy of the cities array. The reverse() method is then applied to the copied array, leaving the original array unchanged.

Check out Find the Length of an Array in TypeScript

Manual Array Reversal Using a Loop

For more control over the reversal process, you can manually reverse an array using a loop. This method is particularly useful when you need to perform additional operations during the reversal.

Example:

let cities: string[] = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];
let reversedCities: string[] = [];

for (let i = cities.length - 1; i >= 0; i--) {
    reversedCities.push(cities[i]);
}

console.log(reversedCities); // Output: ["Phoenix", "Houston", "Chicago", "Los Angeles", "New York"]

In this example, a for loop iterates over the cities array from the last element to the first, pushing each element into the reversedCities array.

Here is the exact output in the screenshot below:

How to Reverse an Array in TypeScript

Read Remove an Item from an Array in TypeScript

Reversing Arrays with Custom Logic

Sometimes, you might need to reverse an array based on custom logic. For instance, you might want to reverse only a portion of the array or apply specific conditions while reversing.

Example:

let cities: string[] = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix", "Philadelphia"];
let start: number = 1;
let end: number = 4;

while (start < end) {
    [cities[start], cities[end]] = [cities[end], cities[start]];
    start++;
    end--;
}

console.log(cities); // Output: ["New York", "Houston", "Chicago", "Los Angeles", "Phoenix", "Philadelphia"]

In this example, only a portion of the cities array is reversed. The while loop swaps the elements between the start and end indices until the entire specified portion is reversed.

Check Get the Last Element of an Array in TypeScript

Performance Considerations While Reversing a TypeScript Array

When working with large arrays, performance can become a concern. The built-in reverse() method is generally efficient, but if you are implementing custom logic, be mindful of the time complexity of your approach.

Example:

let largeArray: number[] = Array.from({ length: 1000000 }, (_, i) => i + 1);
console.time("reverse");
largeArray.reverse();
console.timeEnd("reverse"); // Output: reverse: Xms

This example uses the console.time() and console.timeEnd() methods to measure the time taken to reverse a large array. This can help you understand the performance implications of your reversal logic.

Check out Get the First Element of an Array in TypeScript

TypeScript Reverse an Array Examples

Now, let me show you some real examples of reversing an array in TypeScript.

Reverse User Data

Suppose you have an application that displays a list of recent activities performed by users. To show the most recent activities first, you might need to reverse the array of activities.

Example:

interface Activity {
    id: number;
    description: string;
    timestamp: Date;
}

let activities: Activity[] = [
    { id: 1, description: "Logged in", timestamp: new Date("2024-11-01T10:00:00Z") },
    { id: 2, description: "Viewed profile", timestamp: new Date("2024-11-01T10:05:00Z") },
    { id: 3, description: "Edited settings", timestamp: new Date("2024-11-01T10:10:00Z") },
];

let recentActivities: Activity[] = activities.slice().reverse();
console.log(recentActivities);

In this example, the activities array is reversed to display the most recent activities first, without modifying the original array.

Reverse Data for Visualization

If you are working with data visualization libraries, you might need to reverse data arrays to display charts or graphs in a specific order.

Example:

let salesData: number[] = [100, 200, 150, 300, 250];
let reversedSalesData: number[] = salesData.slice().reverse();

// Use reversedSalesData with a charting library to display data in reverse order

In this scenario, the salesData array is reversed to meet the requirements of a charting library.

Conclusion

In this tutorial, I explained different methods to reverse an array in TypeScript. The built-in reverse() method is efficient for in-place reversal, while creating a new reversed array ensures the original array remains unchanged. For custom reversal logic, loops and conditional statements provide flexibility. Do let me know in the comment below if this tutorial helps you.

You may also like: