Shoes sorted except for one pair that are facing the wrong direction.
Photo by Martin Adams on Unsplash

Javascript .sort() Method

Hyrum Butler
5 min readJan 22, 2021

I recently had a first round technical interview in Javascript. It went well, we discussed and demonstrated everything you might imagine would be talked about in such an interview; event bubbling/delegation, hoisting, DOM manipulation.

However, it wasn’t all peachy and I’m sure you’ve already clued yourself in on what my hang-up in the interview was by the title of this blog post alone.

That’s right, the sort method. A fundamental method in javascript.

Don’t get me wrong, I’ve used the .sort() method many times throughout my coding journey. I have to admit though, it had been awhile since I had implemented it in any projects. In that moment during the interview I thought how odd it was that I couldn’t remember the last time I had used it.

I just haven’t had a problem that couldn’t be solved with a .filter() or .reduce(). Those methods aren’t solving the same problems but I often see code where a developer is using a .sort() along with a .pop() or a .shift(), and are essentially building a .reduce() or .filter().

Nonetheless this post is focusing on .sort() and some of the “gotchas” you might encounter when implementing it for the first time. Or some reminders if you haven’t used it in awhile.

Let’s get an example:

unsortedArr = [3, "2001", "2000", 2000, 45, 444, 1, "a", "3", "B"]

unsortedArr.sort()

will return

[1, "2000", 2000, "2001", 3, "3", 444, 45, "B", "a"]

If you’re thinking, “Wait a minute. That’s not sorted.” You’re right! But actually you’re wrong. And it’s a common misconception among developers coming across this method early on. The problem is that we don’t know how it’s being sorted, not yet…

Spool of thread
Photo by Steve Johnson on Unsplash

Sort converts everything to a string first when not supplied a compare function.

More specifically all the items in the array are compared against the UTF-16 code units order. If UTF-16 code units is new to you then I recommend this quick read giving a high level explanation of the topic. For now know that every character you can type has a hexadecimal representation and the order of a character in the UTf-16 code units list determines the order of our items in the array returned from unsortedArr.sort().

We can immediately see one issue with this as B comes before a in our example output. Why did that happen?

Because uppercase and lowercase characters have different utf-16 codes. So while lowercase b would have come after a, an uppercase B will come before a lowercase a.

A compare function to the rescue.

Even when the list you are wanting to sort is small and you know what the outcome will be it is strongly encouraged that you provide a compare function. Apart from ensuring that your code functions as intended, it will help future developers going through your code, including your future self.

A compare function looks like this:

function compareFunction(a, b) {
return a - b;
}

It’s that easy.

Now let’s put this into action in our example sort method and write this more succinctly with an arrow function.

unsortedArr.sort((a, b) => a — b);

which returns [1, 3, "3", 45, 444, "2000", 2000, "2001", "a", "B"]

If you’re wondering why 3 comes before "3" but "2000" comes before 2000 it’s only because of the order that those numbers were listed in the original unsortedArr array. Which illustrates an important point in any work with code, that experimentation is necessary with any new skill or technology.

Sorting objects.

While we’re taking a look at comparison functions it is important to note that an array of objects can be sorted as well. In this case we have to choose a value on the objects in the array for which to compare.

For example:

var items = [
{ name: 'Hyrum', age: 21 },
{ name: 'Linda', age: 37 },
{ name: 'Nicolette', age: 45 },
{ name: 'Alec', age: -12 },
{ name: 'Toeknee', age: 13 },
{ name: 'Chiba' }
];
items.sort((a, b) => a.age - b.age)

will return,

[
{ name: 'Alec', age: -12 },
{ name: 'Toeknee', age: 13 },
{ name: 'Hyrum', age: 21 },
{ name: 'Linda', age: 37 },
{ name: 'Nicolette', age: 45 },
{ name: 'Chiba' }
]

Notice that and objects that do not have a key-value pair as specified by the compare function are moved to the bottom and not sorted.

Your compare function your way.

If you would prefer that your array is in descending order then you simply flip the position of the “a” and the “b” in your comparison function.

Remember that the first “a” and “b” that are comma separated are only parameters and so should not be switched. See the example below:

So

var items = [
{ name: 'Hyrum', age: 21 },
{ name: 'Linda', age: 37 },
{ name: 'Nicolette', age: 45 },
{ name: 'Alec', age: -12 },
{ name: 'Toeknee', age: 13 },
{ name: 'Chiba' }
];
items.sort((a, b) => b.age - a.age)

yeilds

[
{ name: 'Nicolette', age: 45 },
{ name: 'Linda', age: 37 },
{ name: 'Hyrum', age: 21 },
{ name: 'Toeknee', age: 13 },
{ name: 'Alec', age: -12 },
{ name: 'Chiba' }
]

Conclusion.

When using the javascript .sort() method be sure to include a compare function. The compare function can be altered to sort the items of an array in the way that best suits your needs (asc., desc.).

We can sort arrays of objects by a specified value. Any objects that don’t have the specified key-value pair will be returned at the end of the array in the order in which they were listed in the original array.

And I’ll add to this that the .sort() method sorts the array in place. So If you will need to access the original array later in your code, or just for best practice, be sure to make a copy of the array and to run the .sort() method on the copy.

Be sure that you take time to experiment with methods, languages and frameworks before using them in your code. Test for edge cases and try your hardest to break the method. Make the results give you something unexpected. It’s not enough just to read through the documentation. That is only the start to adding a method to your developer toolkit.

--

--

Hyrum Butler
Hyrum Butler

Written by Hyrum Butler

I love code! I love riddles! I love logic! Please reach out to me in regards to any of these topics.

No responses yet