r1webs r1webs - 1 year ago 201
Javascript Question

Javascript Sort key value pair object based on value

I have an object like below. Trying to rearrange it in ascending order based on value. Similar to Javascript array sort method.

var masterList = {
"1": "google",
"2": "yahoo",
"3": "msn",
"4": "stackoverflow",
"5": "github",
"6": "jsfiddle",
"7": "amazon",
"8": "ebay"

Please let me know the better solution...

Answer Source

JavaScript objects have no order. Even though most browsers do iterate in the same order the properties were created, there's no guarantee, so sorting is not supported on objects.

See here for more info: Does JavaScript Guarantee Object Property Order?

You might also be interested in what John Resig has got to say on the matter.

If you need a sort-able list, you'll have to store it as an array of objects:

var masterList = [
    { key: 1, val: "google" },
    { key: 2, val: "yahoo" },
    { key: 3, val: "msn" },
    { key: 4, val: "stackoverflow" },
    { key: 5, val: "github" },
    { key: 6, val: "jsfiddle" },
    { key: 7, val: "amazon" },
    { key: 8, val: "ebay" }

Then, to sort them, just use the regular array's sort method:

masterList = masterList.sort(function (a, b) {
    return a.val.localeCompare( b.val );

Here's the fiddle: http://jsfiddle.net/ASrUD/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download