Open In App

JavaScript Array sort() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The sort() method in JavaScript arranges the elements of an array in place and returns the sorted array. By default, it sorts the elements alphabetically as strings. If numerical sorting is required, a custom comparison function can be provided as an argument.

Array sort() Method Syntax

arr.sort(compareFunction);

Array sort() Method 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.

Array sort() Method Return value

This method returns the reference of the sorted original array.

Array sort() Method Examples

Example 1: Sorting an array of strings

This example shows the use of the sort() function.

JavaScript




// JavaScript to illustrate sort() function
function func() {
 
    // Original string
    let arr = ["Geeks", "for", "Geeks"]
 
    console.log(arr);
    // Sorting the array
    console.log(arr.sort());
}
func();


Output

[ 'Geeks', 'for', 'Geeks' ]
[ 'Geeks', 'Geeks', 'for' ]


Explanation:

The sort() method rearranges the elements of the arr array alphabetically, producing the output ["Geeks", "Geeks", "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




// 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

Javascript




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 to 9). Then comes 0, followed by 100, 20, 30, and 5.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.

Javascript




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 subtracts b from a. If the result is negative, a comes before b in the sorted array; if positive, b comes before a; if zero, their relative order remains unchanged.
  • By providing this custom comparison function to the sort() method, JavaScript sorts the array numbers 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.

Supported Browsers:



Last Updated : 05 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads