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
};
This could be a simple way to handle it as a real ordered object. Not sure how slow it is. also might be better with a while loop.
And then I found this invert function from: http://nelsonwells.net/2011/10/swap-object-key-and-values-in-javascript/
So
Couln't find answer above that would both work and be SMALL, and would support nested objects (not arrays), so I wrote my own one :) Works both with strings and ints.
Usage:
ECMAScript 2017 introduces
Object.values / Object.entries
. As the name suggests, the former aggregates all the values of an object into an array, and the latter does the whole object into an array of[key, value]
arrays; Python's equivalent ofdict.values()
anddict.items()
.The features make it pretty easier to sort any hash into an ordered object. As of now, only a small portion of JavaScript platforms support them, but you can try it on Firefox 47+.
I am following the solution given by slebetman (go read it for all the details), but adjusted, since your object is non-nested.