JavaScript - Sort key value pair object based on value?



By using JavaScript’s native array methods and functions, we can easily create custom sorting algorithms that will work for any type of object. In this article, we will discuss how to use these techniques in order to sort an object's key-value pairs by value.

A key-value pair in JavaScript such as maps, dictionaries stores one value (the "key") associated with another value (the "value"). It can be used to store and access data quickly, as each element has its own unique identifier.

For sorting key value pair object based on the value, we use sort() method in JavaScript.

Using sort() in JavaScript

The sort() method in JavaScript is used to sort the elements of an array in place and returns the sorted array. The default sort order is ascending.

Syntax

Following is the syntax of sort()

array.sort(compareFunction)

Example

In the following example, we are performing a sort() method after first storing the things as an array of objects and then performing a regular sort() method.

<!DOCTYPE html>
<html>
<body>
   <script>
      var obj = {
         "1": "Apple",
         "2": "Yatch",
         "3": "Ducati",
         "4": "Benz",
      };
      var arr = [];
      for (var key in obj) {
         if (obj.hasOwnProperty(key)) {
            arr.push(obj[key]);
         }
      }
      document.write(arr.sort());
   </script>
</body>
</html>

When the script gets executed, it will generate an output consisting of an array of objects printed in ascending order according to the event, which was triggered on executing the script.

Example

Considering the example, we used Object.keys(obj) to access the object keys in an array and then sorted that array of objects based on the length of each item.value present in it.

<!DOCTYPE html>
<html>
<body>
   <p id="tutorial"></p>
   <script>
      const obj = {
         "1": [11, 234, 343],
         "2": [3],
         "3": [123, 245],
         "4": [1111, 2222, 3333, 4444]
      };
      const array = Object.keys(obj).reduce((array, key) => {
         array.push({ key: key, value: obj[key] });
         return array;
      }, [])
      const sortedArray = array.sort((x, y) => x.value.length - y.value.length);
      document.getElementById("tutorial").innerHTML=JSON.stringify(sortedArray);
   </script>
</body>
</html>

On running the above script, the web-browser displays the array on the webpage sorted based on their length in ascending order, which was caused by the event that was triggered at the time of execution.

Example

Consider the following example, where we are executing the script to sort the key value pair objects based on the value.

<!DOCTYPE html>
<html>
<body>
   <script>
      var myObj = {
         'U': 'avatar',
         'J': 'bheem',
         'M': 'tilak'
      },
      keys = [],
      k, i, len;
      for (k in myObj) {
         if (myObj.hasOwnProperty(k)) {
            keys.push(k);
         }
      }
      keys.sort();
      len = keys.length;
      for (i = 0; i < len; i++) {
         k = keys[i];
         document.write(k + ':' + myObj[k]+"<br>");
      }
   </script>
</body>
</html>

When the script gets executed, the event gets triggered, making the array objects get sorted based on their key-value pair in ascending order on the web-browser.

Example

Execute the below code to sort key value pair objects based on their values.

<!DOCTYPE html>
<html>
<body>
   <p id="tutorial"></p>
   <script>
      var details = [
         { studentId: 100, name: "John" },
         { studentId: 110, name: "Adam" },
         { studentId: 120, name: "Carol" },
         { studentId: 130, name: "Bob" },
         { studentId: 140, name: "David" }
      ];
      details = details.sort(function (obj1, obj2) {
         return obj1.name.localeCompare(obj2.name);
      });
      document.getElementById("tutorial").innerHTML=JSON.stringify(details);
   </script>
</body>
</html>

On running the above script, the event gets triggered, and sorting the given array objects in ascending order based on the alphabetical order on the webpage.


Advertisements