Topic Overview and Learning Goal

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.

Introduction to TypeScript's sort function

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:

let friends: string[] = ["Tom", "Jerry", "Mickey", "Donald"];
friends.sort();

console.log(friends);
// Output: ["Donald", "Jerry", "Mickey", "Tom"]

Sorting numbers works a bit differently:

let numbers: number[] = [5, 1, 8, 3];
numbers.sort();
console.log(numbers); // Output: [1, 3, 5, 8]

numbers = [15, 1, 100, 3];
numbers.sort();

console.log(numbers); // Why is the output [ 1, 100, 15, 3 ] ??

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:

let numbers: number[] = [15, 1, 100, 3];
numbers.sort((a: number, b: number) => a - b); // This will sort numbers in ascending order

console.log(numbers); // Output: [1, 3, 15, 100]
Custom Sorting with TypeScript's Sort Function

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:

let scores: number[] = [60, 90, 82, 100, 56];
scores.sort((a: number, b: number) => b - a);

console.log(scores); // Output: [100, 90, 82, 60, 56]

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.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal