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
How to Sort/Order keys in JavaScript objects ?
In JavaScript, objects store key-value pairs, but their keys aren't automatically sorted. While we can't directly use the sort() method on objects like we do with arrays, we can sort the keys and create a new object with the sorted key-value pairs.
Below, we will learn various methods to sort object keys in ascending and descending order.
Using sort() Method to Order Keys
We can use Object.keys() to get all object keys as an array, sort that array, then reconstruct the object with sorted keys.
Syntax
let allKeys = Object.keys(originalObject);
allKeys.sort();
let sortedObj = {};
for (let i = 0; i < allKeys.length; i++) {
sortedObj[allKeys[i]] = originalObject[allKeys[i]];
}
Example: Sorting Keys in Ascending Order
<html>
<body>
<h2>Sorting object keys in <i>ascending order</i></h2>
<div id="output"></div>
<button onclick="sortObjectKeys()">Sort Object Keys</button>
<script>
let testObj = {
prop7: "Value7",
prop1: "Value1",
prop4: "Value4",
prop2: "Value2",
prop6: "Value6",
prop3: "Value3",
prop5: "Value5"
};
function sortObjectKeys() {
let allKeys = Object.keys(testObj);
allKeys.sort();
let sortedObj = {};
for (let i = 0; i < allKeys.length; i++) {
sortedObj[allKeys[i]] = testObj[allKeys[i]];
}
let output = document.getElementById('output');
output.innerHTML = "<h3>Sorted Object:</h3>";
for (let key in sortedObj) {
output.innerHTML += `Key: ${key} | Value: ${sortedObj[key]}<br>`;
}
}
</script>
</body>
</html>
Example: Sorting Keys in Descending Order
<html>
<body>
<h2>Sorting object keys in <i>descending order</i></h2>
<div id="output"></div>
<button onclick="sortDescending()">Sort Keys Descending</button>
<script>
let testObj = {
z: 50,
a: 10,
x: 40,
b: 30,
t: 20,
h: 21
};
function sortDescending() {
let allKeys = Object.keys(testObj);
allKeys.sort().reverse(); // Sort then reverse for descending order
let sortedObj = {};
for (let key of allKeys) {
sortedObj[key] = testObj[key];
}
let output = document.getElementById('output');
output.innerHTML = "<h3>Descending Sorted Object:</h3>";
for (let key in sortedObj) {
output.innerHTML += `Key: ${key} | Value: ${sortedObj[key]}<br>`;
}
}
</script>
</body>
</html>
Using sort() and reduce() Methods
The reduce() method provides a more functional approach to create the sorted object in a single chain of operations.
Syntax
let sortedObj = Object.keys(originalObject)
.sort()
.reduce((accumulator, key) => {
accumulator[key] = originalObject[key];
return accumulator;
}, {});
Example: Using reduce() Method
<html>
<body>
<h2>Sorting object keys using <i>sort() and reduce()</i> methods</h2>
<div id="output"></div>
<button onclick="sortWithReduce()">Sort with Reduce</button>
<script>
let houseObj = {
window: 6,
rooms: 4,
solar: true,
color: "aqua",
bedRooms: 2,
kitchen: true,
storeRoom: 1
};
function sortWithReduce() {
let sortedObj = Object.keys(houseObj)
.sort()
.reduce((tempObj, key) => {
tempObj[key] = houseObj[key];
return tempObj;
}, {});
let output = document.getElementById('output');
output.innerHTML = "<h3>Sorted Object with Reduce:</h3>";
for (let key in sortedObj) {
output.innerHTML += `Key: ${key} | Value: ${sortedObj[key]}<br>`;
}
}
</script>
</body>
</html>
Comparison of Methods
| Method | Readability | Performance | Use Case |
|---|---|---|---|
| for loop + sort() | Good | Faster | Simple sorting needs |
| reduce() + sort() | Excellent | Slightly slower | Functional programming style |
Key Points
- Objects don't maintain insertion order in older JavaScript versions
- Object.keys() returns keys as strings, sorted alphabetically by default
- Use reverse() after sort() for descending order
- Both methods create new objects rather than modifying the original
Conclusion
Sorting object keys requires extracting keys with Object.keys(), sorting them, and reconstructing the object. The for-loop method offers better performance, while reduce() provides cleaner, more functional code.
