Latest web development tutorials

JavaScript sort () Method

Array Object Reference JavaScript Array Object

Examples

Sorting an array:

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

fruits output:

Apple,Banana,Mango,Orange

try it"

Definition and Usage

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

Sort order may be a letter or number, and press the ascending or descending order.

The default sort order is alphabetical in ascending order.

Note: When the numbers are in alphabetical order "40" will be ranked in the "5" front.

Using digital ordering, you must as a parameter called through a function.

Function Specifies the number is in ascending or descending order.

They say it may be difficult to understand, you can learn more about it at the bottom of this page instances.

NOTE: This method changes the original array!.


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support sort ().


grammar

array.sort( sortfunction )

Parameter Values

参数 描述
sortfunction 可选。规定排序顺序。必须是函数。

return value

Type 描述
Array 对数组的引用。请注意,数组在原数组上进行排序,不生成副本。

technical details

JavaScript Version: 1.1


More examples

Examples

Number Sequencing (numeric and ascending order):

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

fruits output:

1,5,10,25,40,100

try it"

Examples

Number Sequencing (digital and descending):

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

fruits output:

100,40,25,10,5,1

try it"

Examples

Number Sequencing (letters and descending order):

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

fruits output:

Orange,Mango,Banana,Apple

try it"


Array Object Reference JavaScript Array Object