The Wayback Machine - https://web.archive.org/web/20240926181319/https://www.geeksforgeeks.org/javascript-array-sort-method/
Open In App

JavaScript Array sort() Method

Last Updated : 09 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

JavaScript Array sort() Method- FAQs

What is the use of the array sort () method in JavaScript?

The sort() method arranges the elements of an array in place and returns the sorted array. By default, it sorts elements as strings and converts elements to strings if they are not already.

What does array sort () return?

The sort() method in JavaScript returns the sorted array after arranging its elements according to the default or provided sorting order. It modifies the original array and does not create a new one.

What is the time complexity of the sort() method in JavaScript?

The time complexity of sort() is generally O(n log n), where n is the number of elements in the array. However, this can vary based on the implementation and browser.

Does sort() modify the original array?

Yes, sort() modifies the original array. It sorts the elements of the array in place and returns the sorted array.

Does sort() handle edge cases like undefined or null values?

Yes, sort() handles undefined and null values by treating them as undefined when comparing (ECMAScript specification).




Previous Article
Next Article

Similar Reads

What is the use of the Array.sort() method in JavaScript ?
The Array.sort() method is used to sort the elements of an array in place and returns the sorted array. Example: Here, the sort() method is called on an array of numbers. By default, sort() sorts elements as strings, so it sorts the numbers based on their Unicode code points. As a result, the numbers are sorted in ascending order. The sorted array
1 min read
How to Sort an Array using JavaScript when Array Elements has Different Data Types ?
Sorting an array in JavaScript is the process of arranging the elements of the array in a certain order. Generally sorting in an array is to arrange the elements in increasing or decreasing order. It is a common task, however, when an array contains different data types such as numbers, strings, and booleans, sorting becomes a little more complicat
3 min read
How To Sort An Array Without Mutating The Original Array In JavaScript?
Sorting arrays is a common task in JavaScript, especially when you need to present data in a specific order. However, maintaining the original array is often necessary especially if the original data will be required later in your code. In this article we'll see how we can sort an array in JavaScript while keeping the original array unmodified. The
2 min read
JavaScript typedArray.sort() Method
The typedArray.sort() is an inbuilt function in JavaScript which is used to sort the elements of the given typedArray and return the new typedArray with the sorted elements. Syntax: typedArray.sort(); Parameter: It does not accept any parameters. Return value: It returns the new typedArray with the sorted elements. Example: C/C++ Code // Creating s
1 min read
How toSorted() method is different from sort() in JavaScript
In JavaScript, sort() and toSorted() methods do the same job as sorting but toSorted() does not change the original array. sort() method changes the original array. Below we have explained both the methods. Table of Content Sort() MethodtoSorted() MethodSort() Method:The sort() method is a built-in method for arrays in JavaScript that directly modi
2 min read
JavaScript Sort() Method
The sort() method in JavaScript sorts the elements of an array in place and returns the sorted array. By default, it sorts the elements as strings in ascending order. A custom comparison function can be provided to determine the sort order for different data types. Examples: Input: let arr = ["Manish", "Rishabh", "Nitika", "Harshita"];Output: Harsh
2 min read
Javascript Program to Check if it is possible to sort the array after rotating it
Given an array of size N, the task is to determine whether its possible to sort the array or not by just one shuffle. In one shuffle, we can shift some contiguous elements from the end of the array and place it in the front of the array.For eg: A = {2, 3, 1, 2}, we can shift {1, 2} from the end of the array to the front of the array to sort it.A =
3 min read
JavaScript TypeError - Invalid Array.prototype.sort argument
This JavaScript exception invalid Array.prototype.sort argument occurs if the parameter of Array.prototype.sort() is not from either undefined or a function which sorts accordingly. Message: TypeError: argument is not a function object (Edge) TypeError: invalid Array.prototype.sort argument (Firefox) Error Type: TypeError Cause of the Error: The ar
1 min read
Javascript Program to Count rotations required to sort given array in non-increasing order
Given an array arr[] consisting of N integers, the task is to sort the array in non-increasing order by minimum number of anti-clockwise rotations. If it is not possible to sort the array, then print "-1". Otherwise, print the count of rotations. Examples: Input: arr[] = {2, 1, 5, 4, 3}Output: 2Explanation: Two anti-clockwise rotations are required
3 min read
Is JavaScript Array Sort Stable ?
Javascript Array Sort is stable: As of version 10 (or ECMAScript 2019), the specification requires Array.prototype.sort to be stable. In javascript, stable sorting is if an array objects with (key, value) pair has equal keys appear in the same order in sorted output as they appear in the input data set. Therefore it is reliable for the sorting of k
3 min read
Sort an array in reverse order JavaScript
Sorting is a basic algorithm that is used in many programming languages. Most languages provide in-built methods to sort an array. In JavaScript we use the sort() method to sort an array in ascending order. To sort an array in the reverse order that is descending order there are no built-in methods to perform this task but we can combine different
3 min read
How to Sort a Multidimensional Array in JavaScript by Date ?
Sorting a Multidimensional Array by date consists of ordering the inner arrays based on the date values. This needs to be done by converting the date representation into the proper comparable formats and then applying the sorting function to sort the array in ascending or descending order. Below are the possible approaches: Table of Content Using l
2 min read
How to Sort JSON Array in JavaScript by Value ?
Sorting is the process of arranging elements in a specific order. In JavaScript, you can sort a JSON array by value using various methods as listed and discussed below with their practical implementation. Table of Content Using sort() FunctionUsing Array.prototype.reduce()Using Bubble SortUsing sort() FunctionIn this approach, we are using Object.v
3 min read
Sort Mixed Alpha/Numeric array in JavaScript
Sorting a mixed alpha/numeric array in JavaScript involves arranging the elements in a specified order, typically lexicographically (dictionary order) for strings and numerically for numbers. When these types are mixed, a custom sort function is required to effectively handle comparisons between different types. In this article, we will explore mul
3 min read
Sort array of objects by string property value in JavaScript
In this article, we will see how to sort an array of objects by string property value in JavaScript. The array of objects can be sorted by using a user-defined function. Here we have some common approaches to sorting an array of objects by string property value Table of Content Approach 1: Using sort() with a custom compare functionApproach 2: sort
4 min read
Sort an Object Array by Date in JavaScript
To sort an Object Array by Date in JavaScript, we have different approaches. We are going to learn how to sort an Object Array by Date in JavaScript. Below are the approaches to sort an Object Array by Date in JavaScript: Table of Content Using sort method with Date objectsUsing sort() method with getTime() methodUsing a custom sorting functionUsin
4 min read
Sort an array of Strings in JavaScript ?
In this article, we will sort an array of strings in Javascript. we will be given an array having strings as elements we need to sort them according to the series of A-Z. We can sort the strings in JavaScript by the following methods described below: Table of Content Method 1: Using the sort() methodMethod 2: Using JavaScript LoopsMethod 3: Using t
4 min read
How to sort an array of object by two fields in JavaScript ?
We have given an array of objects and the task is to sort the array of elements by 2 fields of the object. There are two methods to solve this problem which are discussed below: Approach 1:First compare the first property, if both are unequal then sort accordingly.If they are equal then do the same for the second property.Example: This example impl
3 min read
Sort an array of objects using Boolean property in JavaScript
Given the JavaScript array containing Boolean values. The task is to sort the array on the basis of Boolean value with the help of JavaScript. There are two approaches that are discussed below: Table of Content Using Array.sort() Method and === OperatorUsing Array.sort() and reverse() MethodsUsing a Custom Comparator Function for ObjectsUsing Array
2 min read
JavaScript Program to Sort an Associative Array by its Values
In Javascript, "arrays" are indexed by numerical values, while "objects" are essentially what you might refer to as associative arrays. It's important to note that "objects" do not have a guaranteed order. In this article, we will learn how can we sort an associative array by its values. Table of Content Using sort() methodUsing Object.entries meth
4 min read
JavaScript Program to Sort the Elements of an Array in Ascending Order
Sorting an array in ascending order means arranging the elements from smallest element to largest element. we will learn to sort an array in ascending order in JavaScript. These are the following methods: Table of Content Using the sort methodUsing a for loopUsing Insertion SortApproach 1: Using the sort methodIn this approach, A function sortAsc t
3 min read
How to Sort an Array of Objects Based on a Key in JavaScript ?
In JavaScript, sorting an array of objects based on the key consists of iterating over the array, applying the sort() method or other approaches, and arranging the array in the desired sorting order. Table of Content Using sort() methodUsing Custom Sorting FunctionUsing Lodash _.orderBy() MethodUsing Intl.CollatorUsing sort() methodIn this approach
3 min read
JavaScript Program to Sort the 2D Array Across Rows
We will see how to sort the 2D Array across rows using a Javascript program. we can sort the 2D Array Across Rows in many ways including Bubble Sort Algorithm, Array.prototype.sort() method, Insertion Sort Algorithm, Using the Selection Sort Algorithm, and Merge Sort Algorithm. Example: Input:[[8 5 7 2],[7 3 0 1],[8 5 3 2],[9 4 2 1]]Output:[[2, 5,
6 min read
How to Sort an Array Based on the Length of Each Element in JavaScript?
Imagine you have a list of words or groups of items, and you want to arrange them in order from shortest to longest. This is a pretty common task in JavaScript, especially when working with text or collections of things. By sorting your list in this way, you can make sense of your data and make it easier to work with or display. Example: Input: ["a
3 min read
JavaScript Program to Find Minimum Number of Swaps to Sort Array
The minimum number of swaps to sort an array is the smallest quantity of element swaps needed to arrange the array in ascending or descending order. This minimizes the number of exchanges and is a key metric in sorting algorithms, as reducing swaps often improves efficiency and performance when organizing data structures. Table of Content Using nes
7 min read
Sort array of objects by single key with date value in JavaScript
In this article, we will see how to sort an array of objects by a single key with a date value in JavaScript. For sorting the array of objects we can use the sort() method which basically calls the callback function as an argument. To sort the array of objects by a single key, we will use the following approaches: Table of Content Using sort() Meth
5 min read
How to sort an array on multiple columns using JavaScript ?
The task is to sort the JavaScript array on multiple columns with the help of JavaScript. There two approaches aree two approaches that are discussed below. Approach 1: Combine the multiple sort operations by OR operator and comparing the strings. For comparing the string, we will use the localeCompare() method. Example: This example implements the
3 min read
JavaScript Program to Sort an Array which Contain 1 to n Values
In this article, we will Sort an array that contains 1 to n values in JavaScript. There are different approaches through which we can sort an array. So, we will mainly cover three different approaches. We will explore all the above methods along with their basic implementation with the help of examples. Approach 1: Using the Set collection in JavaS
4 min read
Javascript Program For Counting Inversions In An Array - Set 1 (Using Merge Sort)
Inversion Count for an array indicates - how far (or close) the array is from being sorted. If the array is already sorted, then the inversion count is 0, but if the array is sorted in the reverse order, the inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j Example:  Input
5 min read
Javascript Program to Sort an array in wave form
Given an unsorted array of integers, sort the array into a wave like array. An array 'arr[0..n-1]' is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= ..... Examples: Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80} Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR {20, 5, 10, 2, 80, 6, 100, 3} OR any other array t
4 min read