简体   繁体   中英

Knockout sort - null values last

I have an observableArray similar to the below:

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):

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. 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.

Here is a jsfiddle for reference: 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. If only one of them is null it will move them down in the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM