How to Sort an Array in TypeScript ?

Array sorting is the process of arranging the elements within an array in a specified order, often either ascending or descending based on predetermined criteria.

Below are the approaches used to sort an array in typescript:

Table of Content

  • Method 1: Using sort method
  • Method 2: Spread Operator
  • Method 3: Custom Sorting Function
  • Method 4: Using a Priority Queue for Custom Sort Order

Method 1: Using sort method

The sort method is a built-in array method in TypeScript that sorts the elements of an array in place. It takes a compare function as an argument, allowing you to define custom sorting criteria.

Example: Sorting an array in ascending and descending order using the sort function.

Javascript
let numbers: number[] = [4, 2, 7, 1, 9];

// Ascending order
numbers.sort((a, b) => a - b);
console.log("Ascending: "+ numbers); 

// Descending order
numbers.sort((a, b) => b - a);
console.log("Descending: "+ numbers);

Output:

Ascending: 1,2,4,7,9
Descending: 9,7,4,2,1

Method 2: Spread Operator

This method involves creating a copy of the array using the spread operator (…) and then using array methods like sort. This approach keeps the original array unchanged and produces a new sorted array.

Example: Sorting an array in ascending and descending order using the sort with help of spread operator to keep the original array unchanged.

Javascript
let numbers: number[] = [4, 2, 7, 1, 9];

// Ascending order
let sortedAscending = [...numbers].sort((a, b) => a - b);
console.log("Ascending: " + sortedAscending); 

// Descending order
let sortedDescending = [...numbers].sort((a, b) => b - a);
console.log("Descending: " + sortedDescending);

Output:

Ascending: 1,2,4,7,9
Descending: 9,7,4,2,1

Method 3: Custom Sorting Function

We can define a custom sorting function based on our specific criteria and use it with the sort method. This method is useful when sorting complex data structures or when a custom sorting logic is required.

Example: Sorting the detail of person using defined custom sorting function based upon our requirement.

Javascript
let detail: { name: string; age: number }[] = [
{ name: "ABC", age: 30 },
{ name: "XYZ", age: 25 },
{ name: "MNP", age: 35 },
];

// Sort by age in ascending order
detail.sort((a, b) => a.age - b.age);
console.log(detail);

Output:

[
{ name: 'XYZ', age: 25 },
{ name: 'ABC', age: 30 },
{ name: 'MNP', age: 35 }
]

Method 4: Using a Priority Queue for Custom Sort Order

For more complex sorting scenarios, especially when dealing with prioritized sorting where certain elements need to be pushed to the front or back based on custom logic, a Priority Queue can be a useful data structure. In TypeScript, we can implement a Priority Queue using a class where the sorting logic is encapsulated in its functionality. This method is particularly useful when you have a large dataset and need an efficient way to maintain sorted order as elements are added or removed.

Here’s an example of using a Priority Queue to sort elements based on a custom priority:

JavaScript
class PriorityQueue<T> {
    private data: T[] = [];

    constructor(private comparator: (a: T, b: T) => number) {}

    push(item: T): void {
        this.data.push(item);
        this.data.sort(this.comparator);
    }

    pop(): T | undefined {
        return this.data.shift();
    }

    peek(): T | undefined {
        return this.data[0];
    }

    size(): number {
        return this.data.length;
    }
}

// Example usage:
let pq = new PriorityQueue<number>((a, b) => a - b);

// Adding elements
pq.push(10);
pq.push(5);
pq.push(15);

// Accessing elements in sorted order
console.log(pq.pop());  
console.log(pq.pop());  
console.log(pq.pop());

Output:

5
10
15




Contact Us