Sorting Arrays in JavaScript

JavaScript Array sort method is a powerful method using which we can sort arrays of numbers, strings, and even objects. This article will cover the sort method in detail, including its syntax, parameters, and how it works.

Array sort method

The sort method accepts a callback function as an argument and sorts the array in place using that function. The callback function (known as compareFunction) is optional. If we omit the callback function, the sort method will sort the array in ascending order.

Syntax

The syntax of the sort() method is as follows:

The sort() method takes an optional callback function compareFunction. It is a function that specifies how to sort the elements of the array. 

If we omit the compareFunction, it will use the default sort. The default sorting method converts each element into strings (casts them to strings) and compares their values according to the UTF-16 encoding standard.

If the array contains Undefined values, then the sort method moves them to the end of the array.

If the array contains empty slots (the array is sparse), then the sort method moves them to the end of the array and after the undefined values.

The sort method mutates the array. The method changes the element positions in the original array and returns it.

Array sort Examples

Default Sorting 

The following code sorts the array of strings. Since we have yet to provide the compareFunction, the sort method uses the default sort.

The default sort converts everything into strings and sorts them in ascending order.

Note that undefined is pushed to the end of the array.

The following code sorts the array of numbers. As you can see from the output, 7000 has come before 2000, 21 & 5 because the default sort method converts numbers to strings.

Using Sort Compare Function

The default sorting method is useful only if you want to sort the array in ascending order. If you’re going to sort in any other way, you need to provide the custom sorting logic using the compareFunction.

The compareFunction specifies the order in which the elements of an array are sorted. The syntax is as follows:

The function accepts two parameters, a and b. They are two elements of the array that you are comparing. The function should compare them and return a value, which then decides the order of those two values.

If we return a positive value, then a will come after b. If we return a negative value, then b will come after a, and if we return 0, then a and b are equal.

compareFn(a, b) return value sort order
> 0sort a after b
< 0sort a before b
=== 0keep original order of a and b

The compare function will be in the following form.

You should also ensure that the compareFunction does not change the array in any way. It also must return the same result for the same pair of inputs.

Array Sorting using Compare Function

Sorting numbers 

The following code sorts the numbers in ascending order. We do that using the sortNumbers function.

The sortNumbers accept two arguments and return a-b. If a is greater than b, then the return value is positive. Hence a is sorted after b. If b is greater, then the return value is negative. Hence b is sorted after a

We invoke the sort method on the numbers array and pass the sortNumbers as its argument.

We can sort the numbers in descending order by reversing a-b to b-a.

Instead of creating a function, you can create an arrow function.

Sorting strings

The default sort method sorts the strings in ascending order but is case-sensitive.

For Example, “Banana” comes before “apple”

You can use the powerful localeCompare method to implement case insensitive sort, which will sort in ascending order. The localeCompare method returns a negative value if the first string comes before the second string in alphabetical order. It produces a positive value if the first string comes after the second string and 0 if the two strings are equal.

For Descending order, you can reverse the a & b.

For case-sensitive comparison, you can pass the options (optional third argument ) object with the sensitivity: 'case'.

You can also set the locales, the second argument to sort according to your locale.

Sorting Objects

We can sort the array of objects by comparing their properties in the compare function.

The code below shows an array of persons using their age.

The following code sorts the array of persons using their names. It uses the localeCompare() method to compare two name properties.

Sorting Dates

The dates array in the code below stores the dates as strings. Compare function creates a date from them using new Date and subtracts one date from another.

When we subtract two date objects, the result is the difference in milliseconds between the two dates. Hence we can sort them using the difference.

Sorting an Array in Random Order

The below sorts the shuffles of the array in Random order. To do that, we use the random method of the Math object. The random method returns a number between 0 and 1. Hence we use the mean value of 0.5.

Non Mutating Sort

The sort method mutates the array. If you do not want to mutate the original array, you can use the spread operator to create a copy of the array and sort its content.

Sparse arrays & Undefined

The sort method moves the undefined values and empty slots (sparse array) to the back of the array. Empty slots come after the undefined. The sort method will not pass them to the compare function.

Summary

  • The sort method accepts a callback function as an argument and sorts the array using that function.
  • The callback function is optional; if not provided, it will use the default method.
  • The default method converts everything to strings and sorts them alphabetically using UTF-16 encoding
  • The callback function accepts two parameters, a and b, corresponding to the two elements of the array that you are comparing. A positive return value will place a after b, a negative value will place b after a, and 0 will keep the original order.

Reference

Array.sort

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top