Use array.sort() with custom sorter function in JavaScript
Description
By default, the sort()
method puts
the items in ascending order.
The sort()
method calls the
String() casting function on every item and
then compares the strings.
This occurs even if all items in an array are numbers:
var values = [0, 1, 5, 10, 15];
values.sort();
console.log(values);
The code above generates the following result.
From the result we can see that the array is not sorted by numeric value.
Example
The following code shows how to use array.sort() with custom sorter function.
The sort()
method can have a
comparison function that indicates how to sort.
A comparison function accepts two arguments and returns
- a negative number if the first is before the second
- a zero if the arguments are equal,
- a positive number if the first is after the second.
function defaultSort(elementX, elementY)
{/*w w w .java 2s.c om*/
if (elementX < elementY)
return -1;
if (elementX > elementY)
return 1;
return 0;
}
var mixture = new Array("red",4,"blue",2,"green",9);
mixture.sort(defaultSort);
var mj = mixture.join(", ");
console.log(mj);
The code above generates the following result.