/

HTML / CSS / JavaScript Tutorial

JavaScript Array method: sort()

[this page | pdf | back links]

The sort() method (when applied to a JavaScript array) sorts elements of the array.

 

By default, it sorts values as alphabetical strings in ascending order. This does not work well for numbers

 

It has the following syntax with the following parameters. It returns a new array containing the selected elements.

 

array.sort(comparefunction)

 

Parameter

Required / Optional

Description

comparefunction

Optional

A function that defines an alternative sort order, e.g. function(a,b){return a - b} to sort in ascending numerical order or function(a,b){return b - a} to sort in descending numerical order

 


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Arrays


Desktop view | Switch to Mobile