myArray.sort( [ compareFunction ] ) in ECMAScript 262
Sort the array.
Arguments
name | type | description |
---|---|---|
compareFunction | Function | [optional] The comparison function to use |
- Return Type
- Array
Description
The original array is sorted (modified), and a reference to the array is returned.
If no comparison function is supplied, toString()
is called on each element of the array and a text-based, ascending-order comparison is used. For example:
var animals = [ 'ant' , 'cat' , 'boar' , 'aardvark' , 'elephant' ];
var numbers = [ 1 , 200 , 3 , 5 , 4 , 2 , 13 , 22 ];
animals.sort(); // ['aardvark','ant','boar','cat','elephant']
numbers.sort(); // [1,13,2,200,22,3,4,5]
// *** Numbers are converted to strings and compared as 'words' using the default sort
If a custom comparison function is supplied, it will be supplied two arguments, corresponding to two particular elements in the array to be sorted. The function must return -1
if the first argument should come before the second, 1
if it should come after the second argument, or 0
if the two arguments should be considered the same.
Following are two examples showing how to use a custom comparison function:
var numbers = [ 1 , 200 , 3 , 5 , 4 , 2 , 13 , 22 ];
function compareNumbers(a,b){
return (a<b)?-1:(a>b)?1:0;
//the above is the same as:
//if (a<b) return -1;
//else if (a>b) return 1;
//else return 0
}
numbers.sort(compareNumbers); // [1,2,3,4,5,13,22,200]
var people = [];
people.push( { name:'Bob' , age:15 , sex:'M' } );
people.push( { name:'Carol' , age:18 , sex:'F' } );
people.push( { name:'Sue' , age:33 , sex:'F' } );
people.push( { name:'Angie' , age:8 , sex:'F' } );
people.push( { name:'David' , age:12 , sex:'M' } );
people.sort( function(a,b){ return (a.age<b.age)?-1:(a.age>b.age)?1:0 } );
/************************************************************************
people is now:
[
{ name:'Angie', age:8, sex:'F' },
{ name:'David', age:12, sex:'M' },
{ name:'Bob', age:15, sex:'M' },
{ name:'Carol', age:18, sex:'F' },
{ name:'Sue', age:33, sex:'F' }
]
************************************************************************/
function compareSexThenName(a,b){
if (a.sex<b.sex) return -1;
else if (a.sex>b.sex) return 1;
else return (a.name<b.name)?-1:(a.name>b.name)?1:0;
}
people.sort(compareSexThenName);
/************************************************************************
people is now:
[
{name:'Angie', age:8, sex:'F'},
{name:'Carol', age:18, sex:'F'},
{name:'Sue', age:33, sex:'F'},
{name:'Bob', age:15, sex:'M'},
{name:'David', age:12, sex:'M'}
]
************************************************************************/
For a flexible convenience function to generate sorting functions for you, see SortBy.