How to Make a Generic Sorting Function in TypeScript ?
Last Updated :
24 Apr, 2025
Sorting is a fundamental operation in programming, allowing us to organize data in a specific order for easier manipulation and retrieval. In TypeScript, creating a generic sorting function provides flexibility and reusability across different data types.
Using Array.prototype.sort() method
This approach utilizes TypeScript generics along with the built-in sorting method. The function takes an array of type T and an optional comparison function. If no comparison function is provided, the default sorting order is lexicographic (Unicode code point order).
Syntax:
function sortArray<T>(array: T[], compareFn?:
(a: T, b: T) => number): T[] {
return array.slice().sort(compareFn);
}
Example 1: The below code example creates a custom sorting function using the built-in sort() method to sort an array of numbers.
JavaScript
const numbers: number[] = [3, 1, 5, 2, 4];
function sortArray<T>(arr: T[], compareFn:
(a: T, b: T) => number): T[] {
const sortedArray = [...arr];
sortedArray.sort(compareFn);
return sortedArray;
}
function ascendingOrder(a: number, b: number):
number {
return a - b;
}
function descendingOrder(a: number, b: number):
number {
return b - a;
}
console.log("Original Array:", numbers);
console.log("Ascending Order:",
sortArray<number>(numbers, ascendingOrder));
console.log("Descending Order:",
sortArray<number>(numbers, descendingOrder));
Output:
Original Array: [3, 1, 5, 2, 4]
Ascending Order: [1, 2, 3, 4, 5]
Descending Order: [5, 4, 3, 2, 1]
Example 2: The below code example creates a custom sorting function using the built-in sort() method to sort an array of objects.
JavaScript
interface Person {
name: string;
age: number;
}
const people: Person[] = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 35 }
];
function sortArray<T>(arr: T[],
compareFn: (a: T, b: T) => number): T[] {
const sortedArray = [...arr];
sortedArray.sort(compareFn);
return sortedArray;
}
function sortByAge(a: Person, b: Person): number {
return a.age - b.age;
}
console.log("Original Array:", people);
console.log("Sorted by Age:",
sortArray<Person>(people, sortByAge));
Output:
Original Array: [
{ name: Alice, age: 30 },
{ name: Bob, age: 25 },
{ name: Charlie, age: 35}
]
Sorted by Age: [
{ name: Bob, age: 25 },
{ name: Alice, age: 30 },
{ name: Charlie, age: 35}
]
By creating custom sorting logic
Developers can implement custom sorting logic tailored to specific requirements. This might involve sorting based on different object properties, custom data structures, or specific business rules. By providing a custom comparison function, developers have full control over the sorting behavior.
Syntax:
function sortArray<T>(array: T[], compareFn:
(a: T, b: T) => number): T[] {
// Sorting logic based on the provided
// comparison function
}
Example 1: The below code implements the custom sorting logic to sort an array of strings based on the length of the string.
JavaScript
function sortArray<T>(arr: T[],
compareFn: (a: T, b: T) => number): T[] {
const sortedArray = [...arr];
for (let i = 0; i < sortedArray.length - 1; i++) {
for (let j = 0; j < sortedArray.length - 1 - i; j++) {
if (compareFn(sortedArray[j], sortedArray[j + 1]) > 0) {
const temp = sortedArray[j];
sortedArray[j] = sortedArray[j + 1];
sortedArray[j + 1] = temp;
}
}
}
return sortedArray;
}
const strings: string[] =
["banana", "apple", "orange", "kiwi"];
function sortByLength(a: string, b: string):
number {
return a.length - b.length;
}
console.log("Original Array:", strings);
console.log("Sorted by Length:",
sortArray<string>(strings, sortByLength));
Output:
Original Array: ["banana", "apple", "orange", "kiwi"]
Sorted by Length: ["kiwi", "apple", "banana", "orange"]
Example 2: The below code example implements custom sorting logic to sort an array of objects based on the value of a particular value.
JavaScript
interface Person {
name: string;
age: number;
}
function sortArray<T>(arr: T[],
compareFn: (a: T, b: T) => number): T[] {
const sortedArray = [...arr];
for (let i = 0; i < sortedArray.length - 1; i++) {
for (let j = 0; j < sortedArray.length - 1 - i; j++) {
if (compareFn(sortedArray[j], sortedArray[j + 1]) > 0) {
const temp = sortedArray[j];
sortedArray[j] = sortedArray[j + 1];
sortedArray[j + 1] = temp;
}
}
}
return sortedArray;
}
const people: Person[] = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 35 }
];
function sortByLengthAndAge(a: Person, b: Person):
number {
const nameComparison = a.name.length - b.name.length;
if (nameComparison !== 0) {
return nameComparison;
}
return a.age - b.age;
}
console.log("Original Array:", people);
console.log("Sorted by Length and Age:",
sortArray<Person>(people, sortByLengthAndAge));
Output:
Original Array: [
{ name: Alice, age: 30 },
{ name: Bob, age: 25 },
{ name: Charlie, age: 35}
]
Sorted by Length and Age: [
{ name: Bob, age: 25 },
{ name: Alice, age: 30 },
{ name: Charlie, age: 35}
]
Similar Reads
How to Create TypeScript Generic Function with Safe Type Matching ?
In TypeScript, generic functions offer a powerful tool for creating flexible and reusable code that can work with various data types. However, ensuring type safety is crucial to prevent runtime errors and maintain code reliability. These are the following approaches:Table of ContentUsing Type constr
4 min read
How to achieve function overloading in TypeScript ?
In this article, we will try to understand some basic details which are associated with the concept of function/method overloading, further will see how we could implement function overloading in TypeScript. Let us first understand some basic facts involved in function/method Overloading. Function/M
2 min read
Function Overloading With Generics In TypeScript
TypeScript has the ability to overload functions which means multiple signatures may be defined for one single function, this comes in handy when you want a function to behave in a certain way based on the provided parameters. In this article, we will be looking at how function overloading is done u
4 min read
How to Convert a String to enum in TypeScript?
In TypeScript, an enum is a type of class that is mainly used to store the constant variables with numerical and string-type values. In this article, we will learn, how we can convert a string into an enum using TypeScript.These are the two approaches that can be used to solve it:Table of ContentUsi
5 min read
How to Make a Generic Type Optional ?
In TypeScript, creating an optional generic type will make it optional to specify a type at the time of declaring the variables or parameters of that type. These are the different approaches to making a generic type optional: Table of Content By assigning any type to the optional generic typeBy assi
4 min read
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 methodMethod 2: Spread OperatorMethod
3 min read
How to Create Arrays of Generic Interfaces in TypeScript ?
In TypeScript, managing data structures effectively is crucial for building robust applications. Arrays of generic interfaces provide a powerful mechanism to handle varied data types while maintaining type safety and flexibility. There are various methods for constructing arrays of generic interface
3 min read
How to write a function in Typescript ?
Writing a function in TypeScript is similar to writing it in JavaScript but with added parameters and return type. Note that any JavaScript function is a perfectly valid TypeScript function. However, we can do better by adding type.Syntax: Let's see a basic TypeScript function syntax (with two argum
4 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
Interesting Facts About Generics in TypeScript
TypeScript generics provide a powerful way to create reusable, type-safe components and functions that work with multiple types. They improve flexibility, reduce redundancy, and ensure strict type constraints without sacrificing reusability.1. Generics Make Functions FlexibleGenerics allow you to cr
3 min read