how to sort java script object by property value

have a look at below example, here sorting is done by value (integer).
 
var list = {"key1": 111, "key2": 715, "key3": 216, "key4": 10};
var arr = sortObject(list);
 
function sortObject(obj) {
    var arr = [];
    for (var key in obj) {
        if (obj.hasOwnProperty(key )) {
            arr.push({
                'key': key ,
                'value': obj[key ]
            });
        }
    }
    arr.sort(function(a, b) { return a.value - b.value; });
    //use this to sort as strings
    //arr.sort(function(a, b) { a.value.toLowerCase().localeCompare(b.value.toLowerCase()); }); 
    return arr; // returns array
}

No comments:

Post a Comment

Genuine websites to earn money.

If you are interested in PTC sites then this article is for you. I have personally tried many of the sites and found that the best thing ...