Easy Tutorial
❮ Event Onseeking Prop Frame Marginheight ❯

JavaScript sort() Method

JavaScript Array Object

Example

Sorting an array:

fruits output result:

Apple,Banana,Mango,Orange

Definition and Usage

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

The sort order can be either alphabetic or numeric, and either ascending or descending.

By default, the sort order is alphabetic and ascending.

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

To sort numbers, you must call the method with a function as a parameter.

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

This might be hard to understand just by reading, so you can refer to the examples at the bottom of this page for further understanding.

Note: This method changes the original array!


Browser Support

All major browsers support the sort() method.


Syntax

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 order):

fruits output result:

Example

Numeric sorting (numbers and descending order):

fruits output result:

Example

Numeric sorting (alphabetic and descending order):

fruits output result:


JavaScript Array Object

❮ Event Onseeking Prop Frame Marginheight ❯