How to Sort an Array in TypeScript ?
Last Updated :
03 Jun, 2024
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:
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
Similar Reads
How to Clone an Array in TypeScript ?
A cloned array is an array that contains all the items or elements contained by an already existing array in the same order. A cloned array does not affect the original array. If there is any change made in the cloned array it will not change that item in the original array. We can use the following
5 min read
How to Convert a Set to an Array in TypeScript ?
A Set in TypeScript is used to create a particular type of list that does not contain duplicate elements. If any element is repeated more than once it will automatically remove the duplicate existence and consider it only once in the list. In this article, we will convert these types of lists into a
5 min read
How to Declare an Array of Strings in TypeScript ?
Arrays are fundamental data structures in TypeScript, enabling developers to manage collections of elements efficiently. Below are the approaches to declare an Array of strings in TypeScript:Table of ContentSquare Brackets NotationArray ConstructorSquare Brackets NotationUsing square brackets notati
1 min read
How do I Remove an Array Item in TypeScript?
In this article, we will learn about the different ways of removing an item from an array in TypeScript. In TypeScript, an array can be defined using union typing if it contains items of different types. We can use the following methods to remove items from a TypeScript array:Table of ContentUsing t
4 min read
TypeScript Array sort() Method
The sort() method in TypeScript sorts the elements of an array and returns the sorted array. By default, it sorts an array in ascending order. It can take an optional compareFunction to define the sort order, allowing for custom sorting logic.Syntaxarray.sort( compareFunction )Parameter: This method
2 min read
How to Sort a Dictionary by Value in TypeScript ?
In TypeScript, dictionaries are objects that store key-value pairs. Sorting a dictionary by value involves arranging the key-value pairs based on the values in ascending or descending order. The below approaches can be used to accomplish this task: Table of Content Using Object.entries() and Array.s
2 min read
How to Flatten Array of Arrays in TypeScript ?
Array flattening is the process of converting a nested array (an array of arrays) into a single-dimensional array where all the elements are at the same level. In other words, it involves transforming an array that contains other arrays as elements into an array that only contains non-array elements
4 min read
How to Create a Stack in TypeScript using an Array ?
Stack is a linear Data Structure that is based on the LIFO concept (last in first out). There are 5 primary operations in the stack as follows:push method(): This method adds element x to the stack.pop() Method: This method removes the last element of the stack.peek() Method: This method returns the
3 min read
Sort an array of objects in typescript?
We can achieve the sorting in TypeScript using the sort() function which is an inbuilt TypeScript function that is used to sort the elements of an array. Below are a few examples showing the sorting in TypeScript. Example 1: In this example, we will learn how to use the sort function to sort the arr
3 min read
How to Declare an Empty Array in TypeScript?
TypeScript provides a robust type system that allows you to define and manage data structures more effectively than in plain JavaScript. One common task is declaring empty arrays with specific types, ensuring that your array holds only values of the intended type. These are the following ways to dec
2 min read