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 objects by numeric values - JavaScript
Suppose we have an object like this:
const obj = {
key1: 56,
key2: 67,
key3: 23,
key4: 11,
key5: 88
};
We are required to write a JavaScript function that takes in this object and returns a sorted array like this:
const arr = [11, 23, 56, 67, 88];
Here, we sorted the object values and placed them in an array.
Method 1: Using Object.keys() and map()
This approach extracts the keys, maps them to their values, and sorts the resulting array.
const obj = {
key1: 56,
key2: 67,
key3: 23,
key4: 11,
key5: 88
};
const sortObject = obj => {
const arr = Object.keys(obj).map(el => {
return obj[el];
});
arr.sort((a, b) => {
return a - b;
});
return arr;
};
console.log(sortObject(obj));
[ 11, 23, 56, 67, 88 ]
Method 2: Using Object.values() (More Concise)
A cleaner approach using Object.values() to directly get the values:
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 ]
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 | Code Length | Readability | Browser Support |
|---|---|---|---|
| Object.keys() + map() | Longer | More verbose | ES5+ |
| Object.values() | Shorter | Cleaner | ES2017+ |
Conclusion
Use Object.values() for the most concise solution. For older browser support, use Object.keys() with map(). Both methods effectively extract and sort object values.
Advertisements
