Array sort()

In this chapter you will learn:

  1. How to sort a Javascript array
  2. How to create your own function for sorting
  3. 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>

Click to view the demo

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>

Click to view the demo

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>

Click to view the demo

sort() returns a reference to the result array.

Next chapter...

What you will learn in the next chapter:

  1. toString(), toLocaleString() and valueOf Array
  2. toLocaleString() vs toString()
Home » Javascript Tutorial » Array
Array Type
Array creation
Array type detecting
Array iterate
Array Length
Add to Array
Array join
Array concat()
Array every method
Array search from start with indexOf()
Array search from the end with lastIndexOf()
Array filter
Array mapping
Array forEach
Array pop and push
Array shift()
Array reduce()
Array reduceRight()
Array reverse()
Array slice()
Array some()
Array splice()
Array sort()
Array toString()
Array unshift()