Sorting By Functions in TypeScript

Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in TypeScript.

// We'll use the built-in Array.sort() method for sorting

function main() {
    const fruits: string[] = ["peach", "banana", "kiwi"];

    // We implement a comparison function for string lengths
    const lenCmp = (a: string, b: string): number => {
        return a.length - b.length;
    };

    // Now we can call sort with this custom comparison function
    // to sort fruits by name length
    fruits.sort(lenCmp);
    console.log(fruits);

    // We can use the same technique to sort an array of
    // values that aren't built-in types
    interface Person {
        name: string;
        age: number;
    }

    const people: Person[] = [
        { name: "Jax", age: 37 },
        { name: "TJ", age: 25 },
        { name: "Alex", age: 72 },
    ];

    // Sort people by age using Array.sort()
    people.sort((a, b) => a.age - b.age);
    console.log(people);
}

main();

This TypeScript code demonstrates custom sorting using the built-in Array.sort() method. Here’s a breakdown of what’s happening:

  1. We define an array of fruits and create a custom comparison function lenCmp that compares strings based on their length.

  2. We use fruits.sort(lenCmp) to sort the fruits array by string length.

  3. We define a Person interface and create an array of Person objects.

  4. We sort the people array by age using an inline comparison function passed to sort().

To run this TypeScript code, you would typically compile it to JavaScript and then run it with Node.js:

$ tsc sorting-by-functions.ts
$ node sorting-by-functions.js
["kiwi", "peach", "banana"]
[{ name: 'TJ', age: 25 }, { name: 'Jax', age: 37 }, { name: 'Alex', age: 72 }]

This example demonstrates how to use custom sorting functions in TypeScript, which can be applied to both built-in types and custom objects.