Understanding JavaScript's sort() Method

Hero image for Understanding JavaScript's sort() Method. Image by Jan Antonin Kolar.
Hero image for 'Understanding JavaScript's sort() Method.' Image by Jan Antonin Kolar.

JavaScript's Array.prototype.sort() method is a powerful builtin function that allows developers to sort the elements of an array inplace and return the sorted array. Whilst it is widely used for its convenience, it can also lead to unexpected results if not understood properly.


What is prototype.sort()?

In brief, Array.prototype.sort() is a method which belongs to the Array prototype in JavaScript, meaning it is available for use on any array instances. The sort method organises the elements of an array according to a specified comparator function.


How Does It Work?

If no explicit comparator function is provided, sort() converts the elements into strings, and then compares their sequences of UTF16 code unit values.

Here's a basic example of using sort() without a comparator function:

const fruits = ['banana', 'cherry', 'apple'];fruits.sort();console.log(fruits);  //=> ['apple', 'banana', 'cherry']

Here, sort() arranges the elements in lexicographical order.

If you want to use sort() for numerical sorting, you must provide a comparator function that defines the sort order. The comparator function takes two arguments (usually referred to as a and b) and should return a negative, zero, or positive value, depending on the desired order:

const numbers = [4, 2, 5, 1, 3];numbers.sort((a, b) => a - b);console.log(numbers);  //=> [1, 2, 3, 4, 5]

Unexpected Behaviour and Its Causes

One of the things that seems to trip developers when it comes to using sort() is that without a comparator function, sort() can yield unexpected results when you're dealing with numerical values or nonstring objects.

This is because the default sort order is based on string Unicode points, which is not the numerical order most would expect. For example:

const numbers = [10, 5, 2, 1, 9];numbers.sort();console.log(numbers);  //=> [1, 10, 2, 5, 9]

Can you see the problem here? In this instance 10 has been positioned before 2 because the string '10' is lexicographically less than the string '2' when compared character by character ('1' < '2').


Sorting Objects

I go into much more detail about sorting objects in JavaScript in my article here for the sake of this (briefer) overview, though, suffice it to say that if you want to sort an array of objects, you must provide a comparator function to compare the properties you're interested in.

For example:

const items = [  { name: 'Table', price: 120 },  { name: 'Chair', price: 20 },  { name: 'Lamp', price: 50 },];// Sort by price in ascending orderitems.sort((a, b) => a.price - b.price);console.log(items);/* Output:  [    { name: 'Chair', price: 20 },    { name: 'Lamp', price: 50 },    { name: 'Table', price: 120 }  ]*/

Wrapping up

The Array.prototype.sort() method is a versatile function that, when understood and used correctly with a comparator, can sort an array of strings, numbers, or objects. Awareness of its default behaviour is crucial for avoiding unexpected results, especially when dealing with numeric sorts.


Categories:

  1. Development
  2. Front‑End Development
  3. Guides
  4. JavaScript