[NEW] Code Review Agent: Improve your code’s quality, security, and compliance
Home / Blog /
How to Use the Array sort() Method in JavaScript
//

How to Use the Array sort() Method in JavaScript

//
Tabnine Team /
4 minutes /
November 29, 2020

The sort() method, by default, reorganizes a given array into one in which the elements are presented in ascending order according to the English alphabet.

Note: the reverse() method reorganizes a given array into descending order.

Basic Array.sort() example

The below example demonstrates the basic usage of Array.sort():

const fruits = ['peach', 'mango', 'banana', 'strawberry', 'apple'];
console.log(fruits[3]);
// Expected output: strawberry
fruits.sort();
console.log(fruits);
// Expected output:
// ["apple", "banana", "mango", "peach", "strawberry"]
console.log(fruits[3]);
// Expected output: peach

In the example above the fruits array contains five items in a specific order.

The first print to the console is for the item at index 3. As the index count begins at zero, the return value is strawberry.

After this print, the sort method is called, and the order of the items in the array is changed to an ascending alphabetical order. This results in apple being moved to the first item, and strawberry being moved to the end (with a matching reorganization of the other elements of the array as well).

This change is demonstrated with the third print statement, which shows that the item at index 3 is now peach.

Note: sort() changes the order of the original array!

Description

This method operates by converting the array items into strings. It then compares the values of the characters (according to UTF-16) and reorganizes the array in an ascending order. This can lead to two problems:

  1. Case sensitivity”: if banana, for example, was written with a capital B instead of a lower-case b, in the resulting array the capitalized “Banana” would appear before “apple”. This is because the UTF-16 value of capital B (66) is less than that of a lowercase a (97).
  2. Sorting numbers: as array items are converted to strings when the sort() method is called, this means that the resulting sorted values do not necessarily correspond to the numeric values they represent. This is due to the use of UTF-16 for the comparison. This means, for example, that the value of the string ‘34’ is greater than that of “150” because the first character of the converted string, ‘3’, is greater than ‘1’.

The first issue has a straightforward solution – simply ensure all of the elements in the array have the same case, whether that is upper or lower. You can use either the toLowerCase() method or the toUpperCase() method to accomplish this.

The second issue is solved by leveraging a compare function. This is an optional parameter for the sort() method

Syntax

The syntax of Array.sort() is as follows:

Array.sort(compareFunction)

compareFunction (optional): this optional parameter allows you to specify a function that can be used to compare the items in the Array for sorting purposes. If the compareFunction parameter is omitted, the array elements are converted into Strings and compared according to their UTF-16 values.

Compare function

The compare function provides an alternative reorganization mechanism to be used by the sorting process. This function compares two array elements at a time, returning a number that represents the relationship between the two. This number returned is either positive, zero, or negative.

The syntax of the compare function is very simple:

function (a, b) {return a – b}

This sample compare function reorganizes an array of numbers in an ascending order.

The syntax above compares two elements (a & b):

  • If the return value is negative, element a is placed before element b
  • If the return value is zero, the elements stay where they were
  • If the return value is positive, element b is placed after element a

The sort() function will continue to operate until all results are negative.

While an example using a compare function is provided later in this article, it first would be beneficial to examine the behavior that occurs when a compare function is not used.

The example below sorts an array of numbers without using a compare function:

const nums = [13, 45, 55, 34, 100, 23, 86];
nums.sort();
console.log(nums);
// Expected output: [100, 13, 23, 34, 45, 55, 86]

The example above does not use a compare function, meaning that the items in the array are compared based upon their UTF-16 values after being converted into strings.

In the “stringednums array, the first character with the lowest value in UTF-16 is ‘1’. And, since ‘0’ is less than ‘3’, the first value in the “sorted” array is ‘100’. As ‘8’ has the highest UTF-16 value, it is placed at the end of the sorted array. The result returned thus does not match the expectation that you might have when asking to sort an array of numbers.

Compare function example

To resolve this sorting problem with numeric arrays, we provide a compare function as an argument to the sort() method:

nums.sort(function (a, b) { return a - b });
console.log(nums);
// Expected output: [13, 23, 34, 45, 55, 86, 100]

In the example above the sort method is provided with an anonymous compare function that accepts two parametersa and b. Both a and b are items in the array nums to which the sort function has been applied.

The first pair of values examined by the compare function are 13 and 45. The compare function returns the result of 13-45, which is a negative number. Due to this, the value 13 is placed before the value 45 in the sorted array. This process continues until comparisons of all pairs of adjacent numbers in the source array return a negative number.

Sort in a descending order

With a small change to the compare function, we can instead reorganize the array into descending order:

function (a, b) {return b – a}

This sample compare function reorganizes the array into one with a descending order, as seen below:

nums.sort(function (a, b) { return b - a });
console.log(nums);
// Expected output: [100, 86, 55, 45, 34, 23, 13]

Note that this mechanism also works for Strings as well. If the compare function is applied to the fruits array above, the resulting array will be sorted in descending order:

fruits.sort(function (a, b) { return b - a });
console.log(fruits);
// Expected output: ["strawberry", "peach", "mango", "banana", "apple"]

Note: you can achieve the same results using the reverse() method.

 

Related Articles

JavaScript – Arrays Explained

JavaScript – How to use the for…of Statement

JavaScript – How to Determine if a Value is an Array