简体   繁体   中英

Javascript sort array of dictionaries alphabetically with possible null values

I am running into an issue. I am sorting contacts by their first name but sometimes I run into a contact that is missing the first name. Does anyone know how to change this method to make it work? Thanks

This is the sorting method I am using.

function sortAZ(ob1,ob2) {
    var n1 = ob1.firstName.toLowerCase()
    var n2 = ob2.firstName.toLowerCase()
    if (n1 > n2) {return 1}
    else if (n1 < n2){return -1}
    else { return 0}//nothing to split
};

data.sort(sortAZ);
function sortAZ(ob1,ob2) {
    // Handles case they're both equal (or both missing)
    if (obj1 == obj2) {return 0}
    // Handle case one is missing
    if (obj2 == null|| obj2 == "") {return 1}
    if (obj1 == null|| obj1 == "") {return -1}

    var n1 = ob1.firstName.toLowerCase()
    var n2 = ob2.firstName.toLowerCase()
    if (n1 > n2) {return 1}
    else if (n1 < n2){return -1}
    else { return 0}//nothing to split
};

It depends on how you want to treat the objects that do not have that attribute.

But adding this to the top of the sort function will prevent it from comparing non-existent attributes.

if (ob1.firstName == undefined || ob2.firstName == undefined) {
    return 0;
}

Note this is a modification of the answer from PherricOxide. Thanks

function sortAZ(obj1,obj2) {
    // Handles case they're both equal (or both missing)
    if (obj1 == obj2) {return 0}

    // Handle case firstName is missing
    if (obj2.firstName == null || obj2.firstName == "") {return 1}
    if (obj1.firstName == null || obj1.firstName == "") {return -1}

    var n1 = ob1.firstName.toLowerCase()
    var n2 = ob2.firstName.toLowerCase()
    if (n1 > n2) {return 1}
    else if (n1 < n2){return -1}
    else { return 0}//nothing to split
};

Check first for existence of the objects and their properties before comparing. If they miss it, return 1 oder -1 to sort them in the end or on top.

function sortAZ(ob1, ob2) {
    if (!ob1) return -1;
    if (!ob2) return 1;
    // if (ob1 == ob2) return 0; // equal
    if (typeof ob1.firstName != "string") return -1;
    if (typeof ob2.firstName != "string") return -1;

    var n1 = ob1.firstName.toLowerCase()
    var n2 = ob2.firstName.toLowerCase()
    if (n1 > n2) return 1;
    if (n1 < n2) return -1;
    return 0; // equal
}

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