I'm sorting my object by its property ActivityOrder
, which will sometimes contain null
values if the user has not explicitly stated an order which an activity should appear.
Since null
will always appear top most in the sort (unless reversed), it messed up my sort.
The solution I came up with was to sort by the id
if activityOrder
was null since the ID will always be greater than the activityOrder
within our application and then there is some logical order to the sort too.
var data = [{
"id": 150,
"name": "Andrew",
"activityOrder": null
}, {
"id": 151,
"name": "Andrew",
"activityOrder": null
}, {
"id": 152,
"name": "Andrew",
"activityOrder": 1
}];
data = _.sortBy(data, function(o) {
if (o.activityOrder === null)
return o.id;
return o.activityOrder
});
_.each(data, function(x) {
$('#cnt').append("<tr><td>" + x.Name + " - Order " + x.activityOrder + "</td></tr>")
})
I had also tried amending the value if the activityOrder
null to 99999999999 and resetting it back to null after doing whatever. I didn't like the idea of this one.
data = _.sortBy(data, function(o) {
if (o.activityOrder === null)
o.activityOrder = 99999999999;
return o.activityOrder
});
//Do whatever
//Reset Activity Order back
_.each(d, function(o) {
if (o.activityOrder === 99999999999) {
o.activityOrder = null;
}
});
How best would you sort an object array by a property which contains null values?