下划线:基于多个属性的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,John。
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屋!