How to use javascript array sort method with examples

The 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 sort order is ascending and alphabetic.

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

30 will come before 4.

See an example of sort method

Syntax of javascript array sort

The syntax to use array sort method is:

array.sort(sort_function );

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

A simple example of javascript sort array method

Following is a simple example of using 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 sort javascript method, without using the sort_function parameter. See demo by clicking the link 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 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, javascript 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 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 JS 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 javascript 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.

Also see Javascript Array | Javascript splice | Javascript length

Was this article helpful?

Related Articles

Leave A Comment?