JavaScript sort() Method
This tutorial explains how to use the sort() method for the JavaScript Array object. The sort() method returns a sorted copy of an existing array, without making any changes to your original array.
By default, the sort() method sorts array elements "alpha-numerically" (numbers first, then alphabetically). sort() also accept an optional argument to define a custom sorting logic, different from the default alpha-numerical order.
Related array method:
The reverse() method does not sort array elements: rather, it reverses their current order (putting the last element in first position). But reverse() is a powerful complement to the sort() method.
Using the sort() Method without Argument
The easiest, and most common way to use the sort() method is without argument: this means that array elements are going to be sorted alphabetically (numbers first, then other characters and letters).
var arlene = new Array("orange","apple","strawberry","banana");
// Use sort() to return alphabetised array copy
alert( arlene.sort().toString() );
We used toString()
to explicitly convert the returned array to a string. Web browsers' JavaScript interpreters generally perform the conversion automatically for arguments passed to alert()
.
The copy of the array returned by the sort() method is indeed alphabetized; remember that the original array was not modified.
To sort the original array, simply equate it to a sorted copy of itself:
var arlene = new Array("orange","apple","strawberry","banana");
arlene = arlene.sort(); // Original array now sorted
Using the sort() Method with a Function Argument
JavaScript lets you to customize the way the sort() method works by passing a custom function as argument. Our Custom sorting function tutorial shows you how to create custom functions for the JavaScript sort() method.
Test the sort() Method
Interactively test the sort() method by editing the JavaScript code below and clicking the Test sort() Method button.
Browser support for JavaScript sort() method | |||
---|---|---|---|