var obj =
[{
"distance": 7000,
"rating": 2,
"name": 'a'
},
{
"distance": 3470,
"rating": 1,
"name": 'b'
}, {
"distance": 3470,
"rating": 2,
"name": 'c'
}, {
"distance": 3480,
"rating": 5,
"name": 'd'
}, {
"distance": 3490,
"rating": 3,
"name": 'e'
}, {
"distance": 4000,
"rating": 3,
"name": 'f'
}];
I am looking to get the output sorted by distance and if distances are nearer to each other by a value (eg. 10), then sort by rating.
I have tried many ways but nothing works.
obj.sort(function(a, b) {
return (a["distance"] - b["distance"]);
});
obj.sort(function(a, b) {
return (b["distance"] - a["distance"] <= 10 ? 0: 1) || b["rating"] -
a["rating"];
});
In above code, first i tried to sort by distance and then if distance difference is less than 10, i sort by rating. But this does not works correctly.
JSBin link - https://jsbin.com/nawiderebu/edit?html,js,console
I would like to get output as follows:
[
{
"distance": 3470,
"rating": 2,
"name": 'c'
},{
"distance": 3470,
"rating": 1,
"name": 'b'
}, {
"distance": 3480,
"rating": 5,
"name": 'd'
}, {
"distance": 3490,
"rating": 3,
"name": 'e'
}, {
"distance": 4000,
"rating": 3,
"name": 'f'
},{
"distance": 7000,
"rating": 2,
"name": 'a'
}
]