0

我遇到了一个问题。我按联系人的名字对联系人进行排序,但有时我会遇到缺少名字的联系人。有谁知道如何更改此方法以使其正常工作?谢谢

这是我正在使用的排序方法。

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);
4

4 回答 4

1
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
};
于 2012-10-13T10:31:20.327 回答
0

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;
}
于 2012-10-13T10:35:25.250 回答
0

在比较之前首先检查对象及其属性的存在。如果他们错过了,请返回1oder-1以将它们排序在最后或顶部。

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
}
于 2012-10-13T11:31:24.917 回答
0

请注意,这是对 PherricOxide 答案的修改。谢谢

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
};
于 2012-10-13T11:20:51.523 回答