JavaScript sort()Method

Array 对象参考手册JavaScript Array Object

Example

Array sorting:

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

fruitsOutput result:

Apple,Banana,Mango,Orange

Try it Yourself »

Definition and Usage

The sort() method is used to sort the elements of an array.

The sort order can be alphabetical or numeric, and in ascending or descending order.

The default sort order is alphabetical ascending.

Note:When numbers are sorted alphabetically, "40" will come before "5".

For numeric sorting, you must call it by passing a function as an argument.

The function specifies whether the numbers are sorted in ascending or descending order.

This may be hard to understand when put into words; you can learn more about it through the examples at the bottom of this page.

Note:This method changes the original array!


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support sort().


Syntax

array.sort(sortfunction)

Parameter Values

Parameter Description
sortfunction Optional. Specifies the sort order. Must be a function.

Return Value

Type Description
Array A reference to the array. Note that the array is sorted in place and no copy is made.

Technical Details

JavaScript Version: 1.1


More Examples

Example

Numeric sorting (numbers and ascending):

var points = [40,100,1,5,25,10];
points.sort(function(a,b){return a-b});

points output result:

1,5,10,25,40,100

Try it Yourself »

Example

Numeric sorting (numbers and descending):

var points = [40,100,1,5,25,10];
points.sort(function(a,b){return b-a});

points output result:

100,40,25,10,5,1

Try it Yourself »

Example

Numeric sorting (alphabetical and descending):

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

fruits output result:

Orange,Mango,Banana,Apple

Try it Yourself »


Array 对象参考手册JavaScript Array Object

Other Extensions