sort()
Array
instance method
JS Home <<
JS Reference <<
Array <<
sort()
Description
Sorts the elements within an array.
Syntax
Signature | Description |
---|---|
anArray.sort([sortOrderFunction]) | Sorts the elements within an array. |
Parameters
Parameter | Description |
---|---|
sortOrderFunction | Specifies a function that designates a sort order. If omitted sort will be done in lexographic order. |
Examples
The code below creates an array then sorts it without a sort order function.
/*
Create an array of names.
Sort elements.
sortNames = ['Fred', 'Jed', 'Ned', 'Neil', 'Ted'] after sort().
*/
var sortNames = ['Fred', 'Ned', 'Ted', 'Jed', 'Neil'];
alert(sortNames);
sortNames.sort();
alert(sortNames);
The code below creates an array then sorts it using a sort order function.
/*
Create an array of numbers.
Sort elements using a function.
sortNumbers = [1, 2, 3, 4, 5] after sort().
*/
var sortNumbers = [5, 1, 3, 4, 2];
alert(sortNumbers);
sortNumbers.sort(function(a, b) {
return a - b;
});
alert(sortNumbers);
Related Tutorials
JavaScript Intermediate Tutorials - Lesson 1 - Arrays