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.
This TypeScript code demonstrates custom sorting using the built-in Array.sort()
method. Here’s a breakdown of what’s happening:
We define an array of fruits and create a custom comparison function
lenCmp
that compares strings based on their length.We use
fruits.sort(lenCmp)
to sort the fruits array by string length.We define a
Person
interface and create an array ofPerson
objects.We sort the
people
array by age using an inline comparison function passed tosort()
.
To run this TypeScript code, you would typically compile it to JavaScript and then run it with Node.js:
This example demonstrates how to use custom sorting functions in TypeScript, which can be applied to both built-in types and custom objects.