sort() Method – How to Sort Array Elements in JavaScript
Whenever you use sort() on an array, the method does the following:
- It sorts its calling array’s items in ascending (or descending) order.
- It returns the calling array in its sorted state.
Example of the sort()
Method
const fruitsArray = ["banana", "coconut", "dates", "apple"];
fruitsArray.sort();
// The invocation above will return:// ["apple", "banana", "coconut", "dates"]
The above snippet used sort()
to sort the fruitsArray
in ascending order.
Syntax of the sort()
Method
Here is sort()
’s syntax:
callingArray.sort();
sort()
also accepts an optional argument. Here is the syntax:
callingArray.sort(compareFunction);
function compareFunction(a, b) { /* ... */}
The inline alternative of the above syntax is this:
callingArray.sort(function compareFunction(a, b) { /* ... */});
The arrow function alternative of the above syntax is as follows:
callingArray.sort((a, b) => { /* ... */});
The compareFunction
argument is a comparison function for comparing array elements. We will discuss it in-depth later in this article. For now, though, let’s talk about how sort()
works without an argument.
How sort()
Works without an Argument
Whenever you use sort()
without the optional callback argument, the method will do the following:
- It converts the calling array’s elements to strings.
- It will automatically sort the array items in ascending order, according to each element’s Unicode point value.
Therefore, you may get unexpected outputs if the array’s elements are numbers.
For instance, 3 comes before 100 in the numeral ordering system. But since sort()
converts numbers to strings, “100” comes before “3” in the Unicode ordering system.
Example 1: How to use sort()
without an argument on an array of alphabets
const stringArray = ["F", "A", "B", "D", "E", "C"];
stringArray.sort();
// The invocation above will return:// ["A", "B", "C", "D", "E", "F"]
sort()
sorted the stringArray
in ascending order according to the items’ Unicode point values.
Example 2: How to use sort()
without an argument on an array of numeric strings
const stringArray = ["40", "100", "6", "22", "59", "3300"];
stringArray.sort();
// The invocation above will return:// ["100", "22", "3300", "40", "59", "6"]
sort()
sorted the stringArray
in ascending order according to their Unicode point values.
Example 3: How to use sort()
without an argument on an array of numbers
const numbersArray = [40, 100, 6, 22, 59, 3300];
numbersArray.sort();
// The invocation above will return:// [100, 22, 3300, 40, 59, 6]
sort()
sorted the numbersArray
in ascending order according to their Unicode point values.
By default, sort()
sorts its calling array’s elements in ascending order, according to their Unicode point values. But you can use the comparison function argument to specify the sorting order. Let’s talk more about this now.
How to Specify sort()
’s Sorting Order with the compareFunction
Argument
The compareFunction
argument allows you to define the exact way you want the computer to sort a list of elements.
In other words, whenever you pass a compareFunction
argument to the sort()
method, sort()
will arrange its calling array’s items based on the function’s return values.
Syntax of the compareFunction
Argument
The compareFunction()
accepts two optional parameters. Here is the syntax:
function compareFunction(a, b) { /* ... */}
- Parameters
a
andb
represent the two array itemssort()
is currently comparing. - Parameter
a
represents the first of the two array itemssort()
is currently comparing. - Parameter
b
represents the second of the two array itemssort()
is currently comparing.
How sort()
’s compareFunction
Argument Works
Suppose sort()
is sorting two items using the comparefunction
argument. In that case, here’s what will happen:
sort()
sends the two items to thecompareFunction
.- If the function accepts parameters, it will receive the two items as its parameters
a
andb
, respectively. - Suppose the function returns an
a − b
statement. In that case, the computer will subtract the Unicode point value of elementb
froma
. - If the function returns a positive value, the computer will position element
a
afterb
. - If the function returns a negative value, the computer will place element
a
beforeb
. - Suppose the subtraction returned zero (
0
). In that case, elementa
and elementb
’s positioning will remain unchanged.
Example 1: How to sort an array of two elements in ascending order
const numbersArray = [10, 7];
numbersArray.sort((a, b) => { return a – b;});
console.log(numbersArray);
// The invocation above will return: [7, 10]
The snippet above positioned 10
after 7
because the compareFunction
returned a positive number (3
).
Example 2: How to sort an array of two elements in descending order
const numbersArray = [10, 7];
numbersArray.sort((a, b) => { return b - a;});
console.log(numbersArray);
// The invocation above will return: [10, 7]
The above snippet positioned 10
before 7
because the compareFunction
returned a negative number (-3
).
Example 3: How to sort an array of five elements in ascending order
const numbersArray = [3, 1, 4, -4, 0, 2, 5];
numbersArray.sort((a, b) => { return a - b;});
console.log(numbersArray);
// The invocation above will return:// [-4, 0, 1, 2, 3, 4, 5]
The snippet above sorted the numbersArray
based on the compareFunction
’s return value each time it compares parameters a
and b
.
In other words, the logic sort()
used to sort the numbersArray
has the following form:
const numbersArray = [3, 1, 4, -4, 0, 2, 5];
numbersArray.sort((a, b) => { return a - b;});
/* The numbersArray sorting logic:3 – (1) = positive => sort() places 3 after 1,3 – (4) = negative => sort() places 3 before 4,3 – (–4) = positive => sort() places 3 after –4,3 – (0) = positive => sort() places 3 after 0,3 – (2) = positive => sort() places 3 after 2,3 – (5) = negative => sort() places 3 before 5,*/
How to Use sort()
without Changing the Original Array
The sort()
method is destructive by default. In other words, its default setting is to change the original array. But you can use it in a non-destructive way by creating a shallow copy of the original array before invoking sort()
.
Example 1: How to make sort()
non-destructive with the spread operator
Here’s how you to use the spread operator to make sort()
non-destructive:
- Use the spread operator (
...
) to duplicate the original array into a new one. - Use
sort()
on the new array.
Here’s an example:
// Define an array:const numbersArray = [77, 1000, 9, 300, 23];
// Duplicate the numbersArray into a new array:const newNumbersArray = [...numbersArray];
// Sort the newNumbersArray in ascending order:const sortedVersionOfNewNumbersArray = newNumbersArray.sort((a, b) => { return a - b;});
// Log the sortedVersionOfNewNumbersArray to the console:console.log(sortedVersionOfNewNumbersArray);
// The invocation above will return:// [9, 23, 77, 300, 1000]
// Log the newNumbersArray to the console:console.log(newNumbersArray);
// The invocation above will return:// [9, 23, 77, 300, 1000]
// Log the numbersArray to the console:console.log(numbersArray);
// The invocation above will return:// [77, 1000, 9, 300, 23]
You can see that numbersArray
remained the same while sort()
altered the newNumbersArray
.
The numbersArray
remained unchanged because we did not use sort()
on it. Instead, we invoked sort()
on the newNumbersArray
.
Example 2: How to make sort()
non-destructive with the Array.from()
method
Here’s how you to use Array.from()
to make sort()
non-destructive:
- Use
Array.from()
to duplicate the original array. - Use
sort()
on the new array.
Here’s an example:
// Define an array:const numbersArray = [77, 1000, 9, 300, 23];
// Duplicate the numbersArray:const newNumbersArray = Array.from(numbersArray);
// Sort the newNumbersArray in ascending order:const sortedVersionOfNewNumbersArray = newNumbersArray.sort((a, b) => { return a - b;});
// Log the sortedVersionOfNewNumbersArray to the console:console.log(sortedVersionOfNewNumbersArray);
// The invocation above will return:// [9, 23, 77, 300, 1000]
// Log the newNumbersArray to the console:console.log(newNumbersArray);
// The invocation above will return:// [9, 23, 77, 300, 1000]
// Log the numbersArray to the console:console.log(numbersArray);
// The invocation above will return:// [77, 1000, 9, 300, 23]
You can see that numbersArray
remained the same while sort()
altered the newNumbersArray
.
The numbersArray
remained unchanged because we did not use sort()
on it. Instead, we invoked sort()
on the newNumbersArray
.
Example 3: How to make sort()
non-destructive with the concat()
method
Here’s how you to use concat()
to make sort()
non-destructive:
- Use
concat()
to duplicate the original array into a new one. - Use
sort()
on the new array.
Here’s an example:
// Define an array:const numbersArray = [77, 1000, 9, 300, 23];
// Duplicate the numbersArray into a new array:const newNumbersArray = [].concat(numbersArray);
// Sort the newNumbersArray in ascending order:const sortedVersionOfNewNumbersArray = newNumbersArray.sort((a, b) => { return a - b;});
// Log the sortedVersionOfNewNumbersArray to the console:console.log(sortedVersionOfNewNumbersArray);
// The invocation above will return:// [9, 23, 77, 300, 1000]
// Log the newNumbersArray to the console:console.log(newNumbersArray);
// The invocation above will return:// [9, 23, 77, 300, 1000]
// Log the numbersArray to the console:console.log(numbersArray);
// The invocation above will return:// [77, 1000, 9, 300, 23]
You can see that numbersArray
remained the same while sort()
altered the newNumbersArray
.
The numbersArray
remained unchanged because we did not use sort()
on it. Instead, we invoked sort()
on the newNumbersArray
.
How to Use sort()
to Shuffle an Array
Here’s how to use sort()
to shuffle (reorder) the items of an array:
- Use the
compareFunction
argument to return a positive number, negative digit, or zero at random. - Use
sort()
to sort the array based on thecompareFunction
’s return value.
Here’s an example:
// Define an array:const numbersArray = [1, 2, 3, 4, 5, 6, 7];
// Shuffle the numbersArray:numbersArray.sort(function compareFunction() { return Math.random() - 0.5;});
Here’s what we did in the snippet above:
- We defined an array of seven numbers.
- We used
Math.random() − 0.5
to return a random number between−0.5 and 0.5
. - The
sort()
method sorts thenumbersArray
based on thecompareFunction
’s return values. For instance, while sorting1
and2
, suppose thecompareFunction
returned0.3606023192109793
(a positive number). In that case, the computer will place1
after2
.
Therefore, each time you invoke numbersArray.sort()
, the computer will return a shuffled array similar to this:
/*[ 4, 2, 6, 1, 3, 5, 7 ][ 4, 1, 3, 2, 6, 7, 5 ][ 1, 4, 3, 6, 5, 2, 7 ][ 7, 4, 6, 3, 1, 2, 5 ]*/
Note the following:
- We omitted the
compareFunction
’s parameters because the function gets its return values from theMath.random() − 0.5
statement, not from subtracting parametersa
andb
. - Using the parameters
a
andb
syntax to getcompareFunction
’s output creates a consistent sorting order because the function returns its values by analyzing elements from the calling array. - The
Math.random() − 0.5
syntax generates a mishmash arrangement because the function returns its values based on random analyses. - The
Math.random() − 0.5
code will return a value between−0.5
and0.5
becauseMath.random()
always returns a random numeral between0
(inclusive) and1
(exclusive).
Important Stuff to Know about the sort()
Method
The sort()
method moves all empty slots and undefined
items to the end of the array.
Here’s an example:
const mixedArray = ["F", , "A", undefined, "B", undefined, "D", "E", , "C"];
mixedArray.sort();
// The invocation above will return:// ["A", "B", "C", "D", "E", "F", undefined, undefined, <2 empty slots>]