How to define custom sort function in JavaScript?


Creating custom sort functions in JavaScript can be a great way to customize and optimize your sorting process. By defining a custom sort function, you are able to control the specific order that elements of an array will be sorted in.

This article will explain how to define a custom sort function in JavaScript, provide examples of when it is useful and discuss several tips on how to make sure your sorting process is as efficient as possible.

Typically, this method alters the initial array by shifting certain elements.

Additionally, the sort() method converts the elements of the input array into strings, before sorting them using a string comparison. When you enter an array of numbers, they will first be converted to their string equivalent before being compared.

Custom sort() in JavaScript

The Custom sort() is a method in JavaScript which allows the user to specify their own custom sorting function for an array.

This is useful when you need to sort elements in a specific order, such as alphabetically or numerically in ascending order. The custom sorting function takes two arguments and returns either 1, 0, or -1 depending on how the values should be sorted relative to each other.

Example

In the following example, we are running the script along with the custom sort(). In this case, we declared an array with some names, and then we are performing a custom sort with conditional logic.

<!DOCTYPE html>
<html>
<body>
   <p id="tutorial"></p>
   <script>
      var array = ['BMW', 'BENZ', 'AUDI', 'DUCATI'];
      array.sort(function(x, y) {
         if (x < y) {
            return -1;
         }
         if (x > y) {
            return 1;
         }
         return 0;
      });
      document.getElementById("tutorial").innerHTML= array;
   </script>
</body>
</html>

When the script gets executed, it will generate an output consisting of an array printed on the webpage in ascending order, which was triggered when the event got triggered as soon as the user executed the script.

Example

In the other case, where the script is being run with custom sort(). At first, we created an array with the names "id" and "car." And we are performing a sort for the name "car" and observing the result.

<!DOCTYPE html>
<html>
<body>
   <p id="tutorial"></p>
   <script>
      function sortBy(field) {
         return function(a, b) {
            return (a[field] > b[field]) - (a[field] < b[field])
         };
      }
      let myArr = [
         {id: 23, car: 'wagnor'},
         {id: 40, car: 'dzire'},
         {id: 14, car: 'swift'},
      ]
      myArr.sort(sortBy('car'));
      document.getElementById("tutorial").innerHTML=JSON.stringify(myArr);
   </script>
</body>
</html>

On running the above script, the event gets triggered, performing a sort on the name "car," and displaying the array in ascending order compared with the different mentioned cars.

Example

Let’s look at another example, where we are having an arbitrary sort, assigning the order to an array, and then using indexof.

<!DOCTYPE html>
<html>
<body>
   <p id="tutorial"></p>
   <script>
      var sortOrder = ['tilak', 'bheem', 'avathar'];
      var myArr = [{
         name: 'avathar'
      },
      {
         name: 'tilak'
      },
      {
         name: 'bheem'
      },
      {
         name: 'tilak'
      }
      ];
      myArr.sort(function(a, b) {
         return sortOrder.indexOf(a.name) - sortOrder.indexOf(b.name);
      });
      document.getElementById("tutorial").innerHTML=JSON.stringify(myArr);
   </script>
</body>
</html>

When the script is run, it will produce an output consisting of an array printed on the webbrowser, in the order of the provided arbitrary sort order, that occurred when the event was triggered, and it will sort the array in the provided sort order.

Updated on: 18-Jan-2023

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements