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>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var values = [0, 1, 5, 10, 15];
values.sort();
document.writeln(values); //0,1,10,15,5
</script>
</head>
<body>
</body>
</html>
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>
<html>
<head>
<title>Example</title>
<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>
The comparison function could produce results in descending order:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<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.
Home
JavaScript Book
Essential Types
JavaScript Book
Essential Types
Array:
- The Array Type
- Array Built-in Methods
- Detecting Arrays
- Get and set array values
- Enumerating the Contents of an Array
- Array Length
- Array join() method
- Array concat()
- Array indexOf()
- Array lastIndexOf()
- Array every()
- Array filter() filters array with the given function.
- Array map()
- Array forEach()
- push() and pop():Array Stack Methods
- push(), shift():Array Queue Methods
- Array reduce()
- Array reduceRight()
- reverse():Reordering array
- Array slice()
- Array some()
- Array splice()
- Array sort()
- toString(), toLocaleString() and valueOf Array
- Array unshift()