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
};
Move them to an array, sort that array, and then use that array for your purposes. Here's a solution:
Once you have the array, you could rebuild the object from the array in the order you like, thus achieving exactly what you set out to do. That would work in all the browsers I know of, but it would be dependent on an implementation quirk, and could break at any time. You should never make assumptions about the order of elements in a JavaScript object.
here is the way to get sort the object and get sorted object in return
you can customise your sorting function as per your requirement
For completeness sake, this function returns sorted array of object properties:
Jsfiddle with the code above is here. This solution is based on this article.
Updated fiddle for sorting strings is here. You can remove both additional .toLowerCase() conversions from it for case sensitive string comparation.
Here is one more example:
If I am having a Object like this ,
want to sort it by day order,
we should have the daySorterMap first,
Initiate a separate Object sortedDayObj,
You can return the sortedDayObj
Underscore.js or Lodash.js for advanced array or object sorts
demo