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>
  
Click to view the demo

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>
  
Click to view the demo

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>
  
Click to view the demo

sort() returns a reference to the result array.

Home 
  JavaScript Book 
    Essential Types  

Array:
  1. The Array Type
  2. Array Built-in Methods
  3. Detecting Arrays
  4. Get and set array values
  5. Enumerating the Contents of an Array
  6. Array Length
  7. Array join() method
  8. Array concat()
  9. Array indexOf()
  10. Array lastIndexOf()
  11. Array every()
  12. Array filter() filters array with the given function.
  13. Array map()
  14. Array forEach()
  15. push() and pop():Array Stack Methods
  16. push(), shift():Array Queue Methods
  17. Array reduce()
  18. Array reduceRight()
  19. reverse():Reordering array
  20. Array slice()
  21. Array some()
  22. Array splice()
  23. Array sort()
  24. toString(), toLocaleString() and valueOf Array
  25. Array unshift()