JavaScript Array sort() Method

## JavaScript Reference

Overview

## JavaScript Objects

JS Array JS Boolean JS Date JS Math JS Number JS String JS RegExp JS Global

## Browser Objects

Window Navigator Screen History Location

## HTML DOM Objects

DOM Document DOM Elements DOM Attributes DOM Events

## HTML Objects

DOM Anchor DOM Area DOM Base DOM Body DOM Button DOM Form DOM Frame/IFrame DOM Frameset DOM Image DOM Input Button DOM Input Checkbox DOM Input File DOM Input Hidden DOM Input Password DOM Input Radio DOM Input Reset DOM Input Submit DOM Input Text DOM Link DOM Meta DOM Object DOM Option DOM Select DOM Style DOM Table DOM td / th DOM tr DOM Textarea

# JavaScript Array sort() Method

JavaScript Array Object

## Example

Sort an array:

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

The result of fruits will be:

Apple,Banana,Mango,Orange
Try it yourself »

## Definition and Usage

The sort() method sorts the items of an array.

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

Default sort order is alphabetic and ascending.

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

To perform a numeric sort, you must pass a function as an argument when calling the sort method.

The function specifies whether the numbers should be sorted ascending or descending.

It can be difficult to understand how this function works, but see the examples at the bottom of this page.

Note: This method changes the original array.

## Browser Support

The sort() method is supported in all major browsers.

## Syntax

array.sort(sortfunction)

## Parameter Values

Parameter | Description
--- | ---
sortfunction | Optional. A function that defines the sort order

## Return Value

Type | Description
--- | ---
Array | The Array object, with the items sorted

## Technical Details

JavaScript Version: | 1.1

## More Examples

## Example

Sort numbers (numerically and ascending):

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

The result of points will be:

1,5,10,25,40,100
Try it yourself »

## Example

Sort numbers (numerically and descending):

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

The result of points will be:

100,40,25,10,5,1
Try it yourself »

## Example

Sort numbers (alphabetically and descending):

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

The result of fruits will be:

Orange,Mango,Banana,Apple
Try it yourself »

JavaScript Array Object

## Your suggestion:

Your E-mail (optional):

Page address:

Description:

Close [X]

## Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]
Search w3schools.com:

## WEB HOSTING

Best Web Hosting UK Reseller Hosting Wow! $5 SSD Hosting

## WEB BUILDING

Download XML Editor
FREE Website BUILDER FREE Website Creator

## WEB RESOURCES

Web Statistics Web Validation

## SHARE THIS PAGE