Javascript Sort key value pair object based on value

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/

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)