Open In App

How to Make a Generic Sorting Function in TypeScript ?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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}
]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads