JavaScript Array sort() Method
The sort()
method in JavaScript arranges the elements of an array in place and returns the sorted array. By default, it sorts elements alphabetically, treating them as strings.
However, for numerical sorting, you can provide a custom comparison function. This function dictates the sorting criteria, allowing precise control over the sorting process. `sort()` enhances the efficiency and functionality of JavaScript applications by enabling you to organize array elements according to specific requirements in a professional and formal manner.
Syntax
arr.sort(compareFunction);
Parameters
array
: The array to be sorted.compareFunction
(Optional): A function that defines the sort order. If omitted, the array elements are sorted based on their string Unicode code points.
Return value
This method returns the reference of the sorted original array.
Examples:
Example 1: Sorting an array of strings
This example shows the use of the sort() function.
// JavaScript to illustrate sort() function
function func() {
// Original string
let arr = ["Beginner", "for", "Beginner"]
console.log(arr);
// Sorting the array
console.log(arr.sort());
}
func();
Output
[ 'Beginner', 'for', 'Beginner' ] [ 'Beginner', 'Beginner', 'for' ]
Explanation:
The sort()
method rearranges the elements of the arr
array alphabetically, producing the output ["Beginner", "Beginner", "for"]
.
Example 2: Sorting an array of numbers without compare function
Here, the sort() method arranges the elements of the array in ascending order.
// JavaScript to illustrate sort() function
function func() {
//Original string
let arr = [2, 5, 8, 1, 4]
//Sorting the array
console.log(arr.sort());
}
func();
Output
[ 1, 2, 4, 5, 8 ]
Explanation:
The sort()
method is called on an array of numbers [2, 5, 8, 1, 4]
. The sort()
method will sort the elements alphabetically because no comparison function is provided. Therefore, the output will be [1, 2, 4, 5, 8]
, which is sorted alphabetically based on the string representations of the numbers.
Example 3: Sorting numeric value without compare function
Here, we are sorting numeric value without compare function
let numbers = [20, 5.2, -120, 100, 30, 0]
console.log(numbers.sort())
Output
[ -120, 0, 100, 20, 30, 5.2 ]
Explanation:
When you use the sort()
method without a compare function, JavaScript sorts array elements as strings by default, which may not always produce the expected results for numeric arrays. Let’s break down the sorting process:
- JavaScript converts each element of the array to a string.
- It then compares the UTF-16 code units of each character in the strings and sorts them based on the Unicode code point value.
Here’s what happens with your array:
- The numbers are converted to strings:
["20", "5.2", "-120", "100", "30", "0"]
. - When sorted alphabetically,
-120
comes first because-
has a lower Unicode code point value than digits (0
to9
). Then comes0
, followed by100
,20
,30
, and5.2
.
Example 4: Sorting numeric value with compare function
We can resolve the unexpected error that occurred in the above example by using the sort() method for numerics using the following compare function.
let numbers = [20, 5.2, -120, 100, 30, 0];
/* Logic:
20 - (5.2) = +ve => 5.2 would be placed before 20,
20 - (-120) = +ve => -120 would be placed before 20,
20 - (100) = -ve => 100 would be placed after 20,
20 - (30) = -ve => 30 would be placed after 20,
20 - (0) = +ve => 0 would be placed before 20,
Similarly for every element, we check
and place them accordingly in iterations.
*/
function compare(a, b) {
return a - b;
}
console.log(numbers.sort(compare));
Output
[ -120, 0, 5.2, 20, 30, 100 ]
Explanation:
- The
compare
function subtractsb
froma
. If the result is negative,a
comes beforeb
in the sorted array; if positive,b
comes beforea
; if zero, their relative order remains unchanged. - By providing this custom comparison function to the
sort()
method, JavaScript sorts the arraynumbers
based on the numerical values of its elements.
Please go through this How to Sort Numeric Array using JavaScript?, to know how the javascript array sort function works
We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.