JavaScript sort() | Sort an Array

The JavaScript sort() method is used to sort an array. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>
   
   <script>
      const myArray = ["Boston", "Austin", "Seattle", "Oakland", "Denver"];
      myArray.sort();
      document.getElementById("xyz").innerHTML = myArray;
   </script>
   
</body>
</html>
Output

In above example, elements of the array myArray are sorted in alphabetical order.

JavaScript sort() Syntax

The syntax of sort() method in JavaScript is:

array.sort(compareFun)

The array refers to the array whose elements are going to sort and compareFun is an optional parameter, which is used when we need to define the sort order using a self-defined function. This self-defined function returns any of the following three values:

These return values depends on the arguments given to the function (self-defined). For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>
   
   <script>
      const x = [30, 10, 100, 67, 23];
      x.sort(function(m, n){return m-n});
      document.getElementById("xyz").innerHTML = x;
   </script>
   
</body>
</html>
Output

If we remove the compareFun parameter from the sort() method, used in above example, in this way:

x.sort();

then the output should be:

Output
10,100,23,30,67

It is because, 23 is bigger than 100, as 2 is bigger than 1. Therefore using the function, the return value of a-b or let's say 23-100 gives a negative values, means that 23 comes before 100. Therefore, use compareFun parameter to sort() method, only when sorting an array that contains numbers as its elements.

Sort an Array in Ascending Order

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>
   
   <script>
      const arr = [12, 23, 43, 10, 435, 100, 122];
      arr.sort(function(x, y){return x-y});
      document.getElementById("xyz").innerHTML = arr;
   </script>
   
</body>
</html>
Output

Sort an Array in Descending Order

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>
   
   <script>
      const a = [12, 23, 43, 10, 435, 100, 122];
      a.sort(function(x, y){return y-x});
      document.getElementById("xyz").innerHTML = a;
   </script>
   
</body>
</html>
Output

Sort an Array in Alphabetical Order

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>
   
   <script>
      const myarr = ["Boston", "Austin", "Seattle", "Oakland", "Denver"];
      myarr.sort();
      document.getElementById("xyz").innerHTML = myarr;
   </script>
   
</body>
</html>
Output

JavaScript Online Test


« Previous Tutorial Next Tutorial »