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
};
Another way to solve this:-
//res will have the result array
Try this. Even your object is not having the property based on which you are trying to sort also will get handled.
Just call it by sending property with object.
I made a plugin just for this, it accepts 1 arg which is an unsorted object, and returns an object which has been sorted by prop value. This will work on all 2 dimensional objects such as
{"Nick": 28, "Bob": 52}
...Here is a demo of the function working as expected http://codepen.io/nicholasabrams/pen/RWRqve?editors=001
Just in case, someone is looking for keeping the object (with keys and values), using the code reference by @Markus R and @James Moran comment, just use:
JavaScript objects are unordered by definition (see the ECMAScript Language Specification, section 8.6). The language specification doesn't even guarantee that, if you iterate over the properties of an object twice in succession, they'll come out in the same order the second time.
If you need things to be ordered, use an array and the Array.prototype.sort method.
We don't want to duplicate the entire data structure, or use an array where we need an associative array.
Here's another way to do the same thing as bonna: