I am trying to sort an array of objects through one property. The array is getting sorted properly when I sort it using a compare function. But the order of the array is changing after the sort. What can I do to prevent it?.
I already thought of a solution, where I can separate the data:0 elements into an array and sort the remaining elements and concatenate both. Just wondering whether there is a simple way of doing it?
Note: hex property is a object which I can't use in the compare function. hex can have any value or string.
var arr = [
{hex: "100x213123", data: 0},
{hex: "20x213223", data: 0},
{hex: "30x313123", data: 200},
{hex: "40x413123", data: 0},
{hex: "50x213123", data: 0},
{hex: "60x213123", data: 0},
{hex: "70x213123", data: 100},
{hex: "80x213123", data: 0},
{hex: "90x213123", data: 100},
{hex: "100x213123",data: 100},
{hex: "110x213123", data: 0},
{hex: "120x213123", data: 0}
].sort(function (item1,item2){
return item1.data - item2.data;
});
console.log(JSON.stringify(arr));
Result
[{"hex":"100x213123","data":0},
{"hex":"120x213123","data":0},
{"hex":"110x213123","data":0},
{"hex":"40x413123","data":0},
{"hex":"50x213123","data":0},
{"hex":"60x213123","data":0},
{"hex":"20x213223","data":0},
{"hex":"80x213123","data":0},
{"hex":"90x213123","data":100},
{"hex":"100x213123","data":100},
{"hex":"70x213123","data":100},
{"hex":"30x313123","data":200}]
Expected
[{hex: "100x213123", data: 0},
{hex: "20x213223", data: 0},
{hex: "40x413123", data: 0},
{hex: "50x213123", data: 0},
{hex: "60x213123", data: 0},
{hex: "80x213123", data: 0},
{hex: "110x213123", data: 0},
{hex: "120x213123", data: 0},
{hex: "70x213123", data: 100},
{hex: "90x213123", data: 100},
{hex: "100x213123",data: 100},
{hex: "30x313123", data: 200}]
Any Ideas?