Shailendra Sharma Shailendra Sharma - 6 months ago 23
AngularJS Question

sort javascript object based on multiple property based on there priority

I have an object, i am using

ng-repeat
but need to show item in sortable formate
sorting should be done on the total value if total value is same for multiple item than sorting should be done based of there p1 value if p1 is same than p2 and if p2 is also same then p3.i have already sorted object on based of total value but stuck in priority how to sort on based on multiple object property ?.

i have done sorting on based of value and key but needed help on this complex situation

{ "QVC":{
"p1":0,
"p2":12,
"p3":12,
"total":24,
"org":"QVC"
},
"TURNER & TOWNSEND":{
"p1":12,
"p2":12,
"p3":0,
"total":24,
"org":"TURNER & TOWNSEND"
},
"EDF ENERGY":{
"p1":12,
"p2":0,
"p3":12,
"total":24,
"org":"EDF ENERGY"
},
"TOWERS WATSON":{
"p1":6,
"p2":0,
"p3":6,
"total":12,
"org":"TOWERS WATSON"
},
"VODAFONE UK LTD":{
"p1":0,
"p2":1,
"p3":0,
"total":1,
"org":"VODAFONE UK LTD"
},
"DENPLAN LTD":{
"p1":1,
"p2":0,
"p3":0,
"total":1,
"org":"DENPLAN LTD"
}

}

Answer

You can make an array first and then sort it with Array#sort() and a callback with the wanted sort hierarchy.

var object = { "QVC": { "p1": 0, "p2": 12, "p3": 12, "total": 24, "org": "QVC" }, "TURNER & TOWNSEND": { "p1": 12, "p2": 12, "p3": 0, "total": 24, "org": "TURNER & TOWNSEND" }, "EDF ENERGY": { "p1": 12, "p2": 0, "p3": 12, "total": 24, "org": "EDF ENERGY" }, "TOWERS WATSON": { "p1": 6, "p2": 0, "p3": 6, "total": 12, "org": "TOWERS WATSON" }, "VODAFONE UK LTD": { "p1": 0, "p2": 1, "p3": 0, "total": 1, "org": "VODAFONE UK LTD" }, "DENPLAN LTD": { "p1": 1, "p2": 0, "p3": 0, "total": 1, "org": "DENPLAN LTD" } },
    array = Object.keys(object).map(function (k) { return object[k]; });

array.sort(function (a, b) {
    return a.total - b.total || a.p1 - b.p1 || a.p2 - b.p2 || a.p3 - b.p3;
});

console.log(array);

Comments