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));

Transcript

00:00 This is going to be a quick lesson,

00:01 but it might save you from making a silly

00:03 mistake in according interview.

00:04 Chances are that you will need to sort some input.

00:07 However, the default JavaScript array sort method

00:10 is not very user-friendly.

00:11 So in this lesson we will look at

00:12 how you can use it effectively without messing up.

00:15 So let's go added score,

00:17 the JavaScript sort method sorts its members

00:20 by using Unicode code points.

00:22 For example, hey, we have an array with two strings, hello

00:25 and fam, and if we call array dot sort, we get back an array

00:29 with fam coming before hello

00:31 because that is how they would appear in a dictionary.

00:34 Now the first thing that might catch you of card is

00:36 that array dot sort not only returns the sorted array,

00:39 but also mutates the original array as well.

00:41 As an example, we have a use sorted utility function

00:44 that wants to use the sorted version of an input array.

00:48 Now when we pass our array into that function,

00:50 the sorted version within the function is

00:53 what we would expect with fam first and hello second.

00:55 But what is unexpected is

00:57 that the original array has also been modified

01:00 and is also now sorted.

01:01 Fortunately, if you are using TypeScript, it is easy

01:04 to catch such bugs by annotating your arrays as read only

01:08 so you don't end up mutating it by mistake.

01:10 And now you can see that input sort is giving a compiled

01:13 time error, which we can fix

01:15 by first creating a read version of the input array

01:18 by using the array slice method.

01:20 Now, if you run the code again with this change in place,

01:22 you can see that the sorted array is sorted,

01:25 but the original array is preserved the way that it was.

01:28 Now the second thing to watch out

01:29 for when using array do sort is

01:31 that it uses Unicode code points which might not give the

01:34 results that you expect.

01:36 For example, here we have a simple number array

01:38 with numbers one, three and 22,

01:40 and they look sorted to me already.

01:42 But when we call sort

01:43 and log out the result, you can see that we get 1 22

01:47 and then three, which is wrong

01:49 because three is less than 22.

01:51 But as far as JavaScript is concerned,

01:53 this is actually correct

01:54 because it is first taking those values

01:57 and looking at the string versions.

01:59 And just like AA appears in the dictionary

02:01 before B two two appears before three and

02:05 therefore 22 appears before three.

02:07 Fortunately, all hope is not lost

02:09 because you can provide a custom compare function

02:12 to the JavaScript array sort method.

02:15 This function gets past two items

02:17 that the algorithm is comparing at any given point,

02:19 and you should return a negative value if you feel

02:21 that A is less than B zero if they are

02:24 equal or a positive value.

02:25 If you think that A is greater than B,

02:27 this will result in a correct custom sorting

02:30 in an ascending order.

02:31 Fortunately for numbers, a simple maths

02:33 of A minus P satisfies all of these constraints.

02:37 And with this simple comparative function in place,

02:39 we now get the correct result of three appearing before 22.

02:43 And speaking of algorithm,

02:44 different browsers do have different

02:46 implementations for their sort.

02:47 However, all of them have the runtime of oof

02:50 and log in, which is the ideal case for sorting.

02:53 This custom comparative function is also your key

02:56 to sorting JavaScript objects. For example,

02:58 Here we have a simple array with some of the top movies

03:01 as ranked right now by IMDB with their name

03:05 and their ear of release if you want to sort them by order

03:08 of their release dates.

03:10 We can do that by using the compar function

03:12 and returning a ear minus B do tier.

03:14 And if we log out the movie names,

03:16 now you can see them sorted by their release dates.

03:19 Now, one final trick that I will leave you

03:21 with is when you want to sort items

03:23 by descending order instead of ascending order.

03:25 Now, we can do that by changing the return value,

03:27 but a better approach in my opinion, is to swap the order

03:30 of the arguments in the compar function.

03:32 This makes it easier for others to review your code as well

03:35 as they can see that you are looking for a descending order

03:38 because the arguments are swapped

03:40 and as expected, you can see the movie names

03:42 with the latest movie displayed first.