[英]Knockout sort - null values last
I have an observableArray
similar to the below: 我有一个类似于下面的observableArray
:
self.people = ko.observableArray([
{ firstName: 'Albert', lastName: 'Woods', number: 2 },
{ firstName: 'Barry', lastName: 'Vincent', number: 4 },
{ firstName: 'Jason', lastName: 'Xavier', number: null },
{ firstName: 'Dean', lastName: 'Zebekiah', number: 1 },
{ firstName: 'Marty', lastName: 'Woods', number: 5 },
{ firstName: 'Bill', lastName: 'Vincent', number: 3 },
{ firstName: 'Chris', lastName: 'Jordan', number: null },
{ firstName: 'Ed', lastName: 'Young', number: null },
{ firstName: 'Dave', lastName: 'Zebekiah', number: 5 }
]);
I'm sorting this based on two values - number
, which isn't unique, then lastname
(I understand this can be written in shorthand, I'm just doing it like this for now for readability): 我基于两个值进行排序这- number
,这不是唯一的,那么lastname
(我明白这可以在速记写,我只是在做它像这样为现在的可读性):
self.people.sort(function (a, b) {
if (a.number == b.number) {
if (a.lastName < b.lastName) {
return -1;
} else if (a.lastName > b.lastName) {
return 1;
} else {
return 0;
}
} else {
if (a.number < b.inumberd) {
return -1;
} else if (a.number > b.number) {
return 1;
} else {
return 0;
}
}
});
This all works fine, except I would like all objects that have a number
value of null
to be the last items on the list, rather than first. 这一切工作正常,但我想有一个所有对象number
的值null
是名单上的最后一个项目,而不是第一个。 What is the best way to achieve this? 实现此目标的最佳方法是什么?
I think I need to do something like the following: 我认为我需要执行以下操作:
if (a.number = null){
return 1;
}
if (b.number = null){
return 0;
}
But the issue with this is that it no longer uses lastName
as the secondary sort term for the relevant objects. 但是,这样做的问题在于,它不再使用lastName
作为相关对象的次要排序术语。
Here is a jsfiddle for reference: http://jsfiddle.net/nimaek/7tsfdfxq/ 这是一个jsfiddle供参考: http : //jsfiddle.net/nimaek/7tsfdfxq/
Thanks. 谢谢。
Try this in your fiddle: 在您的小提琴中尝试以下操作:
if (a.number == null && b.number){
return 1;
}
if (b.number == null && a.number){
return -1;
}
If a.number == null
and b.number == null
it will compare names. 如果b.number == null
a.number == null
和b.number == null
,它将比较名称。 If only one of them is null it will move them down in the list. 如果其中只有一个为空,则将其在列表中向下移动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.