JavaScript Array sort method

The sort method is used to sort array elements in JavaScript. The JS sort method takes a parameter, which is a function, that defines how to sort elements of an array. The default sorting order is ascending and alphabetic.

See an example of sort method

If an array contains both numbers and strings then numbers will be sorted first, then strings will be sorted in alphabetic order. The array sort method will sort numbers like that:

30 will come before 4.

Syntax of JavaScript array sorting

The syntax to use array sort method is:

array.sort(sort_function );

The example below will show you how to use the sort_function parameter inside the sort array method.

A simple example of JavaScript sort array method

Following is a simple example of using the sort method. We have created an array of ten elements which is a mix of numbers and letters in the random order.

The array is displayed before and after using the sort JavaScript method, without using the sort_function parameter. See demo by clicking the link or image below:

Experience this example online

You can see that 10 is appearing before 2. While a, c and z are appearing after numbers by simply using the sort array method without specifying sorting order.

An example of array sort by using sort function

The following example shows how to use the sort function to specify sorting order of array elements by using array sort method.

We are using a numeric array of seven elements with random numbers. The resultant array will be sorted in ascending order (including 2 coming before 10) by using the sort method with a function parameter. See the demo online by clicking the link below:

Experience this example online

You can see, we used a function inside sort method that received two parameters (x,y).

An array sort in descending order example

The following example will sort a numeric array in descending order by using a function inside sort array method. We will use the same array as in above example.

Experience this example online

You can see, the array is sorted in descending order by using the sort method.

Further Reading: Javascript Array | The length property