Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
array.sort(compareFunction)
Method 1: Sorting Object Values as Array
In this approach, we extract object values into an array and sort them directly.
<!DOCTYPE html>
<html>
<body>
<script>
var obj = {
"1": "Apple",
"2": "Yacht",
"3": "Ducati",
"4": "Benz",
};
var arr = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(obj[key]);
}
}
document.write("Sorted values: " + arr.sort().join(", "));
</script>
</body>
</html>
Sorted values: Apple, Benz, Ducati, Yacht
Method 2: Sorting by Array Length
This example sorts key-value pairs based on the length of array values using Object.keys() and reduce().
<!DOCTYPE html>
<html>
<body>
<p id="result"></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("result").innerHTML = JSON.stringify(sortedArray, null, 2);
</script>
</body>
</html>
[
{"key":"2","value":[3]},
{"key":"3","value":[123,245]},
{"key":"1","value":[11,234,343]},
{"key":"4","value":[1111,2222,3333,4444]}
]
Method 3: Sorting Keys by Their Values
This approach sorts the object keys based on their corresponding values alphabetically.
<!DOCTYPE html>
<html>
<body>
<script>
var myObj = {
'U': 'avatar',
'J': 'bheem',
'M': 'tilak'
};
var keys = Object.keys(myObj);
keys.sort((a, b) => myObj[a].localeCompare(myObj[b]));
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
document.write(k + ': ' + myObj[k] + "<br>");
}
</script>
</body>
</html>
U: avatar J: bheem M: tilak
Method 4: Sorting Object Array by Property
This example demonstrates sorting an array of objects based on a specific property value.
<!DOCTYPE html>
<html>
<body>
<p id="output"></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("output").innerHTML = JSON.stringify(details, null, 2);
</script>
</body>
</html>
[
{"studentId":110,"name":"Adam"},
{"studentId":130,"name":"Bob"},
{"studentId":120,"name":"Carol"},
{"studentId":140,"name":"David"},
{"studentId":100,"name":"John"}
]
Comparison of Methods
| Method | Use Case | Returns |
|---|---|---|
| Extract Values to Array | Simple value sorting | Sorted array of values |
| Sort by Array Length | Complex comparison criteria | Array of key-value objects |
| Sort Keys by Values | Preserve key-value relationship | Keys sorted by their values |
| Sort Object Arrays | Array of objects sorting | Sorted object array |
Conclusion
JavaScript provides multiple approaches to sort key-value pairs based on values. Choose the method that best fits your data structure and sorting requirements. The sort() method with custom compare functions offers the most flexibility for complex sorting scenarios.
