下划线:sortBy() 基于多个属性 [英] Underscore: sortBy() based on multiple attributes
问题描述
我正在尝试根据多个属性对包含对象的数组进行排序.即,如果两个对象之间的第一个属性相同,则应使用第二个属性来比较这两个对象.例如,考虑以下数组:
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}]
];
按 roomNumber
属性对这些进行排序,我将使用以下代码:
Sorting these by the roomNumber
attribute i would use the following code:
var sortedArray = _.sortBy(patients, function(patient) {
return patient[0].roomNumber;
});
这工作正常,但我该如何处理才能正确排序John"和Lisa"?
This works fine, but how do i proceed so that 'John' and 'Lisa' will be sorted properly?
推荐答案
sortBy
说它是一种稳定的排序算法,因此您应该能够先按第二个属性排序,然后再按您的第一个属性,如下所示:
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();
当第二个 sortBy
发现 John 和 Lisa 的房间号相同时,它会按照找到的顺序保留他们,第一个 sortBy
设置为Lisa, 约翰".
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".
这篇关于下划线:sortBy() 基于多个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!