Instructor: 00:00 If we have an array, we can call sort on the array and log the result, but that doesn't actually sort the numbers numerically, instead it sorts them in lexical order which means a number like 50 will come before the number 6, because 5 is less than 6.

00:22 This is fine for alphabetical sorting, but bad for numbers. To control how the sort function sorts the values, we can pass another function to sort. It'll be passed two vales at a time which we're calling A and B here.

00:37 It's a really common mistake to return true or false from this function, but that's not actually what we need here. What sort needs is a negative number if we want A to be sorted first.

00:47 If we want to return a zero, if the two elements are equal, and return a positive number, if we want B to come first in the array. If we return A minus B here, then this will actually sort in numerically ascending order.

01:05 Then, we can do something like just switch to B minus A to get it this sort in descending order. There we have a custom sort function. We can do whatever kind of sorting we'd like, so say, we want to show all the positive numbers sorted first in the array and all the negative numbers move to the end of the array.

01:24 We can change our comparative function, so that of both B and A are negative, then the sort is normal. If only one of them is negative, then it sorts in the opposite direction. If neither are negative, then it sorts like normal.

01:39 Then, it sorts the path of the number first, ensures the sorted negative numbers at the end of the array. Custom sort functions are also important when sorting strings, especially if those strings contain numbers that we want to sort numerically.

01:56 For example, let's say we have an array of strings from a database, and each represents a floor in the building. If we sort them with just .sort, then it sorts the strings lexically again, which means the 10th floor will sort for the 1st, and so on.

02:12 If we want these sorted in numerical order instead, then we need to provide a custom comparison function, where we can pull out just the numbers with some regex and compare those numbers directly. That works to properly sort the strings as numbers.