Array sort()
In this chapter you will learn:
- How to sort a Javascript array
- How to create your own function for sorting
- How to sort in descending order
Array sort()
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:
<!DOCTYPE html><!-- j a v a 2 s . co m-->
<html>
<head>
<script type="text/javascript">
var values = [0, 1, 5, 10, 15];
values.sort();
document.writeln(values);
</script>
</head>
<body>
</body>
</html>
The code above generates the following result.
From the result we can see that the array is not sorted by numeric value.
Customized sorting 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.
<!DOCTYPE html><!-- java2s . co m-->
<html>
<head>
<script type="text/javascript">
function compare(value1, value2) {
if (value1 < value2) {
return -1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
}
}
var values = [0, 1, 5, 10, 15];
values.sort(compare);
document.writeln(values); //0,1,5,10,15
</script>
</head>
<body>
</body>
</html>
Sort in descending order
The comparison function could produce results in descending order:
<!DOCTYPE html><!-- ja v a 2s . c o m-->
<html>
<head>
<script type="text/javascript">
function compare(value1, value2) {
if (value1 < value2) {
return 1;
} else if (value1 > value2) {
return -1;
} else {
return 0;
}
}
var values = [0, 1, 5, 10, 15];
values.sort(compare);
document.writeln(values); //15,10,5,1,0
</script>
</head>
<body>
</body>
</html>
sort() returns a reference to the result array.
Next chapter...
What you will learn in the next chapter:
Home » Javascript Tutorial » Array