Underscore: sortBy() based on multiple attributes

sortBy says that it is a stable sort algorithm so you should be able to sort by your second property first, then sort again by your first property, like this:

var sortedArray = _(patients).chain().sortBy(function(patient) {
    return patient[0].name;
}).sortBy(function(patient) {
    return patient[0].roomNumber;
}).value();

When the second sortBy finds that John and Lisa have the same room number it will keep them in the order it found them, which the first sortBy set to “Lisa, John”.

Leave a Comment