JavaScript Array sort() Method


The JavaScript array sort() method is used to arrange the array elements in some order. By default, sort() method follows the ascending order.

Javascript array sort() method sorts the elements of an array.

This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

Because of this, the sort() method will produce an incorrect result when sorting numbers.

You can fix this by providing a "compare function" (See "Parameter Values" below).

Syntax

array.sort(compareFunction)

Parameters: This method accept a single parameter as mentioned above and described below:

  • compareFunction: This parameters is used to sort the elements according to different attributes and in the different order.
    • compareFunction(a,b) < 0

      Then a comes before b in the answer.

    • compareFunction(a,b) > 0

      Then b comes before a in the answer.


  • Example

    Sort an array alphabetically, and then reverse the order of the sorted items (descending):

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.sort();
    fruits.reverse();

    Example -