I used sortBy function in underscore.js library.
I have hash, and I tried to sort it by value as the following:
var obj = {x: 2, y: 6, z: 1, q: 4};
_.sortBy(obj)
But the output is as the following:
[1, 2, 4, 6]
But I need to sort it, and return keys with value as the following:
{z: 1, x: 2, q: 4, y: 6}
How can I return sorted hash using sortBy
?
I noticed that sortBy
function return list, so is there another good solution to sort hash or I need to implement function return sorted hash ?
Sort the keys of the hash according to the values: You can also sort the keys of hash according to the given values.
Sort numbers in ascending order: const points = [40, 100, 1, 5, 25, 10]; Sort numbers in descending order: const points = [40, 100, 1, 5, 25, 10]; Find the lowest value: const points = [40, 100, 1, 5, 25, 10]; Find the highest value: const points = [40, 100, 1, 5, 25, 10];
The compare function To sort an array of objects in JavaScript, use the sort() method with a compare function. A compare function helps us to write our logic in the sorting of the array of objects. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.
Introduction to JavaScript Array sort() method By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last. The sort() method casts elements to strings and compares the strings to determine the orders.
There's no such thing as a sorted hash (object) in JavaScript. What you can do is put the keys in an array, iterate that and use the keys to access the object properties.
var keys = Object.keys(obj);
keys.sort(function(a, b) {
return obj[a] - obj[b]
});
keys.forEach(function(k) {
console.log(obj[k]);
});
Related to @Ragnar answer. I got solution to solve the question. And return sorted hash.
Ascending Order
function getSortedHash(inputHash){
var resultHash = {};
var keys = Object.keys(inputHash);
keys.sort(function(a, b) {
return inputHash[a] - inputHash[b]
}).forEach(function(k) {
resultHash[k] = inputHash[k];
});
return resultHash;
}
Descending Order
function getSortedHash(inputHash){
var resultHash = {};
var keys = Object.keys(inputHash);
keys.sort(function(a, b) {
return inputHash[a] - inputHash[b]
}).reverse().forEach(function(k) {
resultHash[k] = inputHash[k];
});
return resultHash;
}
In addition, if you want to return the array in descending order, you can use reverse()
function:
var obj = {x: 2, y: 6, z: 1, q: 4};
var keys = Object.keys(obj);
keys.sort(function(a, b) {
return obj[a] - obj[b]
}).reverse().forEach(function(k) {
console.log(obj[k]);
});
or just like this (thanks to @muistooshort):
var obj = {x: 2, y: 6, z: 1, q: 4};
var keys = Object.keys(obj);
keys.sort(function(a, b) {
return obj[b] - obj[a] //inverted comparison
}).forEach(function(k) {
console.log(obj[k]);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With