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.
Table of Contents
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:
1 2 3 | array.sort([compareFunction]) |
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.
1 2 3 4 5 6 | const fruits = ['Apple', 'Orange', undefined, 'Fig', 'Banana','Mango']; fruits.sort(); console.log(fruits); // [ 'Apple', 'Banana', 'Fig', 'Mango', 'Orange', undefined ] |
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.
1 2 3 4 5 6 | const numbers = [1, 300, 7000, 2000, 21, 5, undefined]; numbers.sort(); console.log(numbers); //[ 1, 2000, 21, 300, 5, 7000, undefined ] |
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:
1 2 3 | compareFn(a, b) |
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 |
---|---|
> 0 | sort a after b |
< 0 | sort a before b |
=== 0 | keep original order of a and b |
The compare function will be in the following form.
1 2 3 4 5 6 7 8 9 10 11 12 | function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } |
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.
1 2 3 4 5 6 7 8 9 10 | const numbers = [1, 300, 7000, 2000, 21, 5, undefined]; numbers.sort(sortNumbers); console.log(numbers); //[ 1, 5, 21, 300, 2000, 7000, undefined ] function sortNumbers(a, b) { return a - b; } |
We can sort the numbers in descending order by reversing a-b
to b-a.
1 2 3 4 5 6 7 8 9 10 11 12 13 | const numbers = [1, 300, 7000, 2000, 21, 5, undefined]; numbers.sort(sortNumbers); console.log(numbers); //[ 7000, 2000, 300, 21, 5, 1, undefined ] function sortNumbers(a, b) { return b - a; } |
Instead of creating a function, you can create an arrow function.
1 2 3 4 5 6 | const numbers = [1, 300, 7000, undefined, 2000, 21, 5 ]; numbers.sort((a,b) => b - a); console.log(numbers); //[ 7000, 2000, 300, 21, 5, 1, undefined ] |
Sorting strings
The default sort method sorts the strings in ascending order but is case-sensitive.
For Example, “Banana” comes before “apple”
1 2 3 4 5 6 | const fruits = ['apple', 'Orange', 'Fig', 'Banana','mango']; fruits.sort(); console.log(fruits); // [ 'Banana', 'Fig', 'Orange', 'apple', 'mango' ] |
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.
1 2 3 4 5 6 | const fruits = ['apple', 'Orange', 'Fig', 'Banana','mango']; fruits.sort((a,b) => a.localeCompare(b)); console.log(fruits); //[ 'apple', 'Banana', 'Fig', 'mango', 'Orange' ] |
For Descending order, you can reverse the a & b.
1 2 3 4 5 6 | const fruits = ['apple', 'Orange', 'Fig', 'Banana','mango']; fruits.sort((a,b) => b.localeCompare(a)); console.log(fruits); //[ 'Orange', 'mango', 'Fig', 'Banana', 'apple' ] |
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.
1 2 3 4 5 6 | const fruits = ['apple', 'Orange', 'Fig', 'Banana','mango']; fruits.sort((a, b) => b.localeCompare(a, undefined, { sensitivity: 'case' })); console.log(fruits); //[ 'Orange', 'mango', 'Fig', 'Banana', 'apple' ] |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | const person = [ { name: "Jeffery", age: 21 }, { name: "Nathan", age: 37 }, { name: "Donna", age: 45 }, { name: "Michael", age: 12 }, { name: "Dennis", age: 13 }, { name: "Frederick", age: 37 }, ]; person.sort((a,b) => a.age - b.age ); console.log(person); //[ // { name: 'Michael', age: 12 }, // { name: 'Dennis', age: 13 }, // { name: 'Jeffery', age: 21 }, // { name: 'Nathan', age: 37 }, // { name: 'Frederick', age: 37 }, // { name: 'Donna', age: 45 } //] |
The following code sorts the array of persons using their names. It uses the localeCompare()
method to compare two name properties.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | const person = [ { name: "Jeffery", age: 21 }, { name: "Nathan", age: 37 }, { name: "Donna", age: 45 }, { name: "Michael", age: 12 }, { name: "Dennis", age: 13 }, { name: "Frederick", age: 37 }, ]; person.sort((a, b) => a.name.localeCompare(b.name) ); console.log(person); //[ // { name: 'Dennis', age: 13 }, // { name: 'Donna', age: 45 }, // { name: 'Frederick', age: 37 }, // { name: 'Jeffery', age: 21 }, // { name: 'Michael', age: 12 }, // { name: 'Nathan', age: 37 } //] |
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.
1 2 3 4 5 6 7 8 9 10 | const dates = ['2022-01-01', '2022-01-03', '2022-01-02']; dates.sort((a, b) => (new Date(b)) - (new Date(a))); console.log(dates); //[ '2022-01-03', '2022-01-02', '2022-01-01' ] dates.sort((a, b) => (new Date(a)) - (new Date(b))); console.log(dates); //[ '2022-01-01', '2022-01-02', '2022-01-03' ] |
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.
1 2 3 4 5 6 7 8 | const numbers = [1, 300, 7000, 2000, 21, 5, undefined]; numbers.sort((a,b) => Math.random() - 0.5 ); console.log(numbers); //[ 2000, 7000, 21, 5, 300, 1, undefined ] |
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.
1 2 3 4 5 6 7 8 9 | const numbers = [3, 1, 4, 1, 5]; const sorted = [...numbers].sort((a, b) => a - b); //sorted array console.log(sorted); //[ 1, 1, 3, 4, 5 ] //no change in original array console.log(numbers); //[ 3, 1, 4, 1, 5 ] |
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.
1 2 3 4 5 6 | const numbers = [1, 300, 7000, undefined,,, 2000, 21, 5 ]; numbers.sort((a,b) => b - a); console.log(numbers); //[ 7000, 2000, 300, 21, 5, 1, undefined ] |
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
andb
, corresponding to the two elements of the array that you are comparing. A positive return value will placea
afterb
, a negative value will placeb
aftera
, and 0 will keep the original order.