Create your own function for sorting in JavaScript

Description

The following code shows how to create your own function for sorting.

Example


<!--  ww w  .  j av  a  2s. co m-->

<!DOCTYPE html>
<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>

Click to view the demo

The code above generates the following result.

Create your own function for sorting in JavaScript
Home »
  Javascript Tutorial »
    Data Type »
      Array
...
Assign undefined value to an array element ...
Assign value to a Two-dimensional array in ...
Call array constructor without new operator...
Change array created with array literal in ...
Change array length with length property in...
Check each value in an array with some() fu...
Check if a variable is array type with Arra...
Check if a variable is array type with inst...
Check if array.sort is case sensitive in Ja...
Concatenate Array elements together in Java...
Concatenate two dimensional array in JavaSc...
Create a case-insensitive comparison in Jav...
Create an array with different type of valu...
Create an array without setting its length ...
Create an empty array with array literal in...
Create array with Array Constructor and set...
Create array with Array Constructor and set...
Create array with array literal notation in...
Create your own function for sorting in Jav...
Delete an array element in JavaScript
Delete with Array splice() in JavaScript
Display Multi-dimensional array in a HTML t...
Do an alphabetical sort() method on strings...
Fill and populate two dimensional array in ...
Filter an array with a condition in JavaScr...
Get a string of the array elements separate...
Get array element value with index in JavaS...
Get the last element in an Array in JavaScr...
Insert with Array splice() in JavaScript
Integer Array Declaration with initializati...
Join array elements together with string se...
Loop through an array with for statement in...
Loop through array and work on each element...
Map array value in JavaScript
Move data from an Array to another in JavaS...
Output array with toString() in JavaScript
Output array with valueOf() in JavaScript
Push form value to a stack in JavaScript
...