If I have a JavaScript object such as:
var list = {
"you": 100,
"me": 75,
"foo": 116,
"bar": 15
};
Is there a way to sort the properties based on value? So that I end up with
list = {
"bar": 15,
"me": 75,
"you": 100,
"foo": 116
};
output = [ { p: 8 }, { c: 2 }, { b: 1 }, { g: 1 } ]
Using query-js you can do it like this
You can find an introductory article on query-js here
Object sorted by value (DESC)
OK, as you may know, javascript has sort() function, to sort arrays, but nothing for object...
So in that case, we need to somehow get array of the keys and sort them, thats the reason the apis gives you objects in an array most of the time, because Array has more native functions to play with them than object literal, anyway, the quick solotion is using Object.key which return an array of the object keys, I create the ES6 function below which does the job for you, it uses native sort() and reduce() functions in javascript:
And now you can use it like this:
Check the sortedMyObject and you can see the result sorted by keys like this:
Also this way, the main object won't be touched and we actually getting a new object.
I also create the image below, to make the function steps more clear, in case you need to change it a bit to work it your way:
An "arrowed" version of @marcusR 's answer for reference
UPDATE: April 2017 - This returns a sorted
myObj
object defined above.Try it here!
UPDATE: October 2018 - Object.entries version
Try it here!