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 the above example, elements of the array myArray are sorted in alphabetical order.

JavaScript sort() syntax

The syntax of the sort() method in JavaScript is:

array.sort(compareFun)

The array refers to the array whose elements are going to be sorted and compareFun is an optional parameter that is 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 depend 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 the 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, and 2 is bigger than 1. Therefore, using the function, the return value of a-b, or, let's say, 23-100, gives a negative value, meaning that 23 comes before 100. Therefore, use the compareFun parameter to the 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 ascending 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 »


Liked this post? Share it!