How to sort an array of object by two fields in JavaScript?


An array of objects is an array that contains all the elements in the form of JavaScript objects. Here, we are said to use an array of objects with two fields that means, have to use objects with two elements as elements of the array.

In this article, we are going to learn about the method of sorting the array of objects by two fields in JavaScript. We can simply use the sort() method of JavaScript to sort the elements of an array and give it a cmp or the comparator function to define the order in which we want to sort the elements of objects in the given array.

Syntax

Following syntax will show you how to use the sort() method with an array to sort its elements −

array_name.sort( comparator_function );

Let us implement it practically and use the sort() method to sort an array of objects by two fields in JavaScript with the help of code example.

Steps

  • Step 1− In the first step, we will add two input elements to the HTML document of number type to get number input from user and then add them to the array in the form of an object.

  • Step 2− In the next step, we will add two different button elements to perform different functionality. The first button will add or insert the elements entered by the user to the array in the form of an object, while the second button will arrange the elements of array such that all the objects are sorted according to the first property of the objects.

  • Step 3− In the third step, we will define a JavaScript function which is going to add the elements with the values entered by the user in the form of object and assign it as an value to the onclick event of the first button defined in the previous step.

  • Step 4− In this step, we will define another JavaScript function which uses the sort() method with a comparator function to sort the elements of the array according to the first property of the objects contained by the array.

  • Step 5− In the last step, we will assign the function defined in the previous step to the onclick event of the second button defined in third step.

Example

The below example will help you to understand the above algorithm as well as the use of the sort() method with comparator function to sort array of objects −

<!DOCTYPE html>
<html lang = "en">
<body>
   <h2>Sort an array of object by two fields in JavaScript</h2>
   <p>Enter any two numbers to insert into objects array:</p>
   <input type = "number" id = "inp1" placeholder = "Number1"> <br><br>
   <input type = "number" id = "inp2" placeholder = "Number2"> <br><br>
   <button id = "add" onclick = "insertArr()"> Add Item to set</button>
   <button id = "btn" onclick = "sortArr()"> click to sort</button>
   <p id = "prev">The initial order of values in array of objects is:</p>
   <p id = "result">The final sorted order of values in array of objects is:</p>
   <script>
      var result = document.getElementById("result");
      var prev = document.getElementById("prev");
      var myArr = [];
      function insertArr() {
         var inp1 = document.getElementById("inp1");
         var val1 = inp1.value;
         var num1 = Number(val1);
         var inp2 = document.getElementById("inp2");
         var val2 = inp2.value;
         var num2 = Number(val2);
         var obj = {
            objNum1: num1,
            objNum2: num2
         }
         myArr.push(obj);
         inp1.value = " ";
         inp2.value = " ";
      }

      function sortArr() {

         for (var item of myArr) {
            prev.innerHTML += " <b> " + JSON.stringify(item) + " </b> ";
         }

         function cmp(a, b) {
            var xa = a.objNum1;
            var xb = b.objNum1;
            var ya = a.objNum2;
            var yb = b.objNum2;

            if (xa == xb) {
               return ((ya < yb) ? -1 : (ya > yb) ? 1 : 0);
            } else {
               return ((xa < xb) ? -1 : 1);
            }
         }

         myArr.sort(cmp);

         for (var item of myArr) {
            result.innerHTML += " <b> " + JSON.stringify(item) + " </b> ";
         }
      }
   </script>
</body>
</html>

In the above example, all the objects of the array will be sorted according to the value of their first property. After entering every value in the input field you have to click the Add item to set button to set or insert values to the array in the form of objects, once you done with inserting values click the click to sort button to sort the elements in the given order.

Let us see one more code example in which we will sort the array elements according to the second property of the objects and write the comparator function very shortly.

Algorithm

The algorithm of the previous example and this example is similar. You just need to perform a minor change in the previous algorithm by replacing the whole code written in the parenthesis of the cmp function with the below code −

return a.objNum2 - b.objNum2 || a.objNum1 - b.objNum1;

The above code will sort the array according to the second property of the objects as well as it will shorten our cmp function. We can also use the same cmp function in the previous example just by interchanging the conditions used with the OR operator.

Example

The below example will sort the elements of the array according to the second property of the objects stored in it −

<!DOCTYPE html>
<html>
<body>
   <h2>Sort an array of object by two fields in JavaScript</h2>
   <p>Enter any two numbers to insert into objects array:</p>
   <input type = "number" id = "inp1" placeholder = "Number1"><br><br>
   <input type = "number" id = "inp2" placeholder = "Number2"><br><br>
   <button id = "add" onclick = "insertArr()">Add Item to set</button>
   <button id = "btn" onclick = "sortArr()">click to sort</button>
   <p id = "prev">The initial order of values in array of objects is:</p>
   <p id = "result">The final sorted order of values in array of objects is:</p>
   <script>
      var result = document.getElementById("result");
      var prev = document.getElementById("prev");
      var myArr = [];

      function insertArr() {
         var inp1 = document.getElementById("inp1");
         var val1 = inp1.value;
         var num1 = Number(val1);
         var inp2 = document.getElementById("inp2");
         var val2 = inp2.value;
         var num2 = Number(val2);
         var obj = {
            objNum1: num1,
            objNum2: num2
         }
         myArr.push(obj);
         inp1.value = " ";
         inp2.value = " ";
      }

      function sortArr() {
         for (var item of myArr) {
            prev.innerHTML += " <b> " + JSON.stringify(item) + " </b> ";
         }

         function cmp(a, b) {
            return a.objNum2 - b.objNum2 || a.objNum1 - b.objNum1;
         }

         myArr.sort(cmp);
         for (var item of myArr) {
            result.innerHTML += " <b> " + JSON.stringify(item) + " </b> ";
         }
      }
   </script>
</body>
</html>

The above example will sort the array elements according to the second property of the stored objects.

Conclusion

In this article, we have learned how we can sort an array of objects by two fields in JavaScript. We have discussed it with the help of two different example, where in the first example, we sort the elements according to the first property of the objects and in the second example, we sort the array according to the second property of the stored objects.

Updated on: 20-Nov-2023

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements