Sorting object with null values underscore sortBy 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("&lt;tr&gt;&lt;td&gt;" + x.Name + " - Order " + x.activityOrder + "&lt;/td&gt;&lt;/tr&gt;")
})


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?
flapdoodle!

if (o.activityOrder === null)
        o.activityOrder = 99999999999;


Dude, don't do this. Really. 



Sorting idiom


Javascript supports sorting pretty much as you'll see in other languages.
Collections have sorting.
Sort functions can take a function delegate for customized sorting.
Typically, compare the desired values and return an integer that means less-than, equal-to, greater-than. Typically -1, 0, 1 respectively. 
handling null does not require converting it to a valid value in your set domain. 
Read the documentation!