JavaScript sorts an array of json objects (in ascending and descending order of a property)

     var data = [{
                name: "Overseas Business Department",
                value: 0.58
            }, {
                name: "Domestic Sales",
                value: 0.36
            }, {
                name: "Internet Center",
                value: 0.78
            }];  

           //Define a comparator -- sort in descending order
            function compare(propertyName) {
                return function(object1, object2) {
                    var value1 = object1[propertyName];
                    var value2 = object2[propertyName];
                    if(value2 < value1) {
                        return -1 ;
                    } else if(value2 > value1) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            }

           data.sort(compare("value"));

data is the sorted data.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324902118&siteId=291194637