Lesson 6
Sorting Arrays With Built-In TypeScript Functions
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:

TypeScript
1let friends: string[] = ["Tom", "Jerry", "Mickey", "Donald"]; 2friends.sort(); 3 4console.log(friends); 5// Output: ["Donald", "Jerry", "Mickey", "Tom"]

Sorting numbers works a bit differently:

TypeScript
1let numbers: number[] = [5, 1, 8, 3]; 2numbers.sort(); 3console.log(numbers); // Output: [1, 3, 5, 8] 4 5numbers = [15, 1, 100, 3]; 6numbers.sort(); 7 8console.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:

TypeScript
1let numbers: number[] = [15, 1, 100, 3]; 2numbers.sort((a: number, b: number) => a - b); // This will sort numbers in ascending order 3 4console.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:

TypeScript
1let scores: number[] = [60, 90, 82, 100, 56]; 2scores.sort((a: number, b: number) => b - a); 3 4console.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.

Explaining the "compare" Function

The compare function sent to sort is a custom function that defines the order in which elements should be arranged in an array. It takes two arguments, a and b, which represent two elements from the array. The function compares these elements and returns:

  • A negative number if a should come before b
  • A positive number if a should come after b
  • Zero if a and b are equal in terms of sorting order

This mechanism allows for custom sorting beyond default lexicographical order, such as numerical sorting or multi-factor sorting.

Multi-Factor Sorting in TypeScript

Great work so far! Now, let's dive a little deeper. Like a shop sorting products first by category, then by price within each category, we can sort arrays on multiple layers using TypeScript's sort() function. This technique is called multi-factor sorting.

Consider an array of objects representing students, with each object containing the student's name and grade:

TypeScript
1type Student = { name: string; grade: number }; 2 3let students: Student[] = [ 4 { name: "Tom", grade: 90 }, 5 { name: "Jerry", grade: 95 }, 6 { name: "Mickey", grade: 90 }, 7 { name: "Donald", grade: 95 } 8];

We can sort this array by grade and name within each grade:

TypeScript
1students.sort((a: Student, b: Student) => { 2 if (a.grade < b.grade) return -1; 3 if (a.grade > b.grade) return 1; 4 5 // Here, 'grade' is the same, so we sort by 'name' 6 if (a.name < b.name) return -1; 7 if (a.name > b.name) return 1; 8 9 return 0; // a and b are equal, remain in same position 10});

Our compare function starts by checking the grade. If the grade of a is less than b, it returns -1, meaning a comes before b. If the grade of a is more than b, it returns 1, so a comes after b.

If grades are identical, our function proceeds to check name. The same principle applies: if a comes before b, it returns -1; otherwise, it returns 1.

Sorting Result

As a result, our students array gets sorted first by grade, then by name within each grade:

TypeScript
1console.log(students); 2/* Output: 3[ 4 { name: 'Mickey', grade: 90 }, 5 { name: 'Tom', grade: 90 }, 6 { name: 'Donald', grade: 95 }, 7 { name: 'Jerry', grade: 95 } 8] 9*/
Lesson Summary and Next Steps

Bravo! You've expanded your knowledge of sorting using TypeScript. We've explored sorting simple and complex arrays, discovered the importance of a compare function, and leveraged TypeScript's type annotations to enhance the reliability and correctness of our functions.

Now, let's put your learning into practice. Make sure you create exercises using your own data to solidify these concepts!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.