Array Sorting in JavaScript

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Array Sorting in JavaScript

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Use readonly

const array = ['hello', 'fam'];

function useSorted(input: readonly string[]) {
const sorted = input.slice().sort();
// ... do something with sorted
console.log('sorted', sorted);
}

useSorted(array);

console.log('original', array);

Sorting Numbers

const example = [1, 3, 22];

example.sort((a, b) => a - b);

console.log(example);

Sorting Objects

/** https://www.imdb.com/chart/top/ */
const movies = [
{
name: "The Shawshank Redemption",
year: 1994
},
{
name: "The Godfather",
year: 1972
},
{
name: "The Dark Knight",
year: 2008
},
{
name: "The Godfather: Part II",
year: 1974
},
];

movies.sort((a, b) => a.year - b.year);

console.log(movies.map(m => m.name));
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

This is going to be a quick lesson, but it might save you from making a silly mistake in according interview. Chances are that you will need to sort some input. However, the default JavaScript array sort method is not very user-friendly. So in this lesson we will look at how you can use it effectively without messing up. So let's go added score, the JavaScript sort method sorts its members by using Unicode code points. For example, hey, we have an array with two strings, hello and fam, and if we call array dot sort, we get back an array with fam coming before hello because that is how they would appear in a dictionary.

00:34

Now the first thing that might catch you of card is that array dot sort not only returns the sorted array, but also mutates the original array as well. As an example, we have a use sorted utility function that wants to use the sorted version of an input array. Now when we pass our array into that function, the sorted version within the function is what we would expect with fam first and hello second. But what is unexpected is that the original array has also been modified and is also now sorted. Fortunately, if you are using TypeScript, it is easy to catch such bugs by annotating your arrays as read only

01:08

so you don't end up mutating it by mistake. And now you can see that input sort is giving a compiled time error, which we can fix by first creating a read version of the input array by using the array slice method. Now, if you run the code again with this change in place, you can see that the sorted array is sorted, but the original array is preserved the way that it was. Now the second thing to watch out for when using array do sort is that it uses Unicode code points which might not give the results that you expect. For example, here we have a simple number array with numbers one, three and 22,

01:40

and they look sorted to me already. But when we call sort and log out the result, you can see that we get 1 22 and then three, which is wrong because three is less than 22. But as far as JavaScript is concerned, this is actually correct because it is first taking those values and looking at the string versions. And just like AA appears in the dictionary before B two two appears before three and therefore 22 appears before three. Fortunately, all hope is not lost because you can provide a custom compare function to the JavaScript array sort method.

02:15

This function gets past two items that the algorithm is comparing at any given point, and you should return a negative value if you feel that A is less than B zero if they are equal or a positive value. If you think that A is greater than B, this will result in a correct custom sorting in an ascending order. Fortunately for numbers, a simple maths of A minus P satisfies all of these constraints. And with this simple comparative function in place, we now get the correct result of three appearing before 22. And speaking of algorithm, different browsers do have different implementations for their sort.

02:47

However, all of them have the runtime of oof and log in, which is the ideal case for sorting. This custom comparative function is also your key to sorting JavaScript objects. For example, Here we have a simple array with some of the top movies as ranked right now by IMDB with their name and their ear of release if you want to sort them by order of their release dates. We can do that by using the compar function and returning a ear minus B do tier. And if we log out the movie names, now you can see them sorted by their release dates. Now, one final trick that I will leave you

03:21

with is when you want to sort items by descending order instead of ascending order. Now, we can do that by changing the return value, but a better approach in my opinion, is to swap the order of the arguments in the compar function. This makes it easier for others to review your code as well as they can see that you are looking for a descending order because the arguments are swapped and as expected, you can see the movie names with the latest movie displayed first.