Welcome back, learners! Today, we will unravel the magic of TypeScript's integration with the sort() function. We will discover how this excellent tool comes into play when managing extensive customer databases or arranging products in an online store. By mastering the sort() function, you can efficiently organize arrays in your code, ensuring a smoother user experience.
Have you ever observed how products in an online shop are arranged? They're sorted in a specific order: alphabetically, by price, by popularity, etc. Similarly, in TypeScript, sorting helps to arrange arrays in a particular order.
Meet the hero of our lesson - the sort() function, a built-in method for sorting arrays. Let's examine how it works in TypeScript:
Sorting numbers works a bit differently:
Everything works well with the first collection, but what happened with [15, 1, 100, 3]? It turns out, TypeScript's sort() function treats numbers as strings by default, sorting them lexicographically! If you want to sort a collection of numbers, ensure you define a compare function with properly typed parameters to achieve accurate results:
The true power of sort() in TypeScript reveals itself when you provide a compare function. This function determines the sorting order. Let's look at an array of scores sorted in descending order:
See? The compare function (a: number, b: number) => b - a helps sort the scores in descending order, with TypeScript ensuring both parameters are of type number.
