
Understanding JavaScript's sort() Method

JavaScript's Array.prototype.sort() method is a powerful built‑in function that allows developers to sort the elements of an array in‑place 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 UTF‑16 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 non‑string 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.
Related Articles

Responsive JavaScript and the matchMedia Method. Responsive JavaScript and the

Sorting Complex Arrays in JavaScript. Sorting Complex Arrays in JavaScript

Using data‑* Attributes and dataset in JavaScript. Using
data‑*Attributes anddatasetin JavaScript
Mastering JavaScript's slice(). Mastering JavaScript's
slice()Static Site Generators. Static Site Generators

Manipulating Strings in JavaScript with split(). Manipulating Strings in JavaScript with
split()
The LeetCode Zigzag Conversion Problem in TypeScript. The LeetCode Zigzag Conversion Problem in TypeScript

3Sum in JavaScript: Two Pointers After Sorting. 3Sum in JavaScript: Two Pointers After Sorting

Controlled vs. Uncontrolled Components in React. Controlled vs. Uncontrolled Components in React

Object.is() vs. Strict Equality in JavaScript. Object.is()vs. Strict Equality in JavaScript
Optimising Vue.js Performance with Lazy Loading and Code Splitting. Optimising Vue.js Performance with Lazy Loading and Code Splitting

Position: sticky in CSS. position: stickyin CSS