I am trying to sort an array with objects based on multiple attributes. I.e if the first attribute is the same between two objects a second attribute should be used to comapare the two objects. For example, consider the following array:
var patients = [
[{name: 'John', roomNumber: 1, bedNumber: 1}],
[{name: 'Lisa', roomNumber: 1, bedNumber: 2}],
[{name: 'Chris', roomNumber: 2, bedNumber: 1}],
[{name: 'Omar', roomNumber: 3, bedNumber: 1}]
];
Sorting these by the roomNumber
attribute i would use the following code:
var sortedArray = _.sortBy(patients, function(patient) {
return patient[0].roomNumber;
});
This works fine, but how do i proceed so that 'John' and 'Lisa' will be sorted properly?
I think you'd better use
_.orderBy
instead ofsortBy
:Simple Example from http://janetriley.net/2014/12/sort-on-multiple-keys-with-underscores-sortby.html (courtesy of @MikeDevenney)
Code
With Your Data
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: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 firstsortBy
set to "Lisa, John".Just return an array of properties you want to sort with:
ES6 Syntax
ES5 Syntax
This does not have any side effects of converting a number to a string.
Perhaps underscore.js or just Javascript engines are different now than when these answers were written, but I was able to solve this by just returning an array of the sort keys.
In action, please see this fiddle: https://jsfiddle.net/mikeular/xenu3u91/
I know I'm late to the party, but I wanted to add this for those in need of a clean-er and quick-er solution that those already suggested. You can chain sortBy calls in order of least important property to most important property. In the code below I create a new array of patients sorted by Name within RoomNumber from the original array called patients.