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
Selected Reading
Sorting a JSON object in JavaScript
In JavaScript, objects themselves cannot be sorted since their properties don't have a guaranteed order. However, we can extract the values from a JSON object and sort them into an array.
Suppose we have an object like this:
const obj = {
key1: 56,
key2: 67,
key3: 23,
key4: 11,
key5: 88
};
We need to write a JavaScript function that takes this object and returns a sorted array of its values:
const arr = [11, 23, 56, 67, 88];
Method 1: Using Object.values() (Recommended)
The simplest approach uses Object.values() to extract values directly:
const obj = {
key1: 56,
key2: 67,
key3: 23,
key4: 11,
key5: 88
};
const sortObjectValues = (obj) => {
return Object.values(obj).sort((a, b) => a - b);
};
console.log(sortObjectValues(obj));
[ 11, 23, 56, 67, 88 ]
Method 2: Using Object.keys() and map()
This method first gets the keys, then maps them to their values:
const obj = {
key1: 56,
key2: 67,
key3: 23,
key4: 11,
key5: 88
};
const sortObject = obj => {
const arr = Object.keys(obj).map(key => obj[key]);
return arr.sort((a, b) => a - b);
};
console.log(sortObject(obj));
[ 11, 23, 56, 67, 88 ]
Sorting in Descending Order
To sort values in descending order, reverse the comparison:
const obj = {
key1: 56,
key2: 67,
key3: 23,
key4: 11,
key5: 88
};
const sortDescending = (obj) => {
return Object.values(obj).sort((a, b) => b - a);
};
console.log(sortDescending(obj));
[ 88, 67, 56, 23, 11 ]
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
Object.values() |
High | Better | ES2017+ |
Object.keys() + map() |
Medium | Good | ES5+ |
Conclusion
Use Object.values() for cleaner, more readable code when extracting and sorting object values. The Object.keys() approach works well for older browser support.
Advertisements
