如何通过ABC对javascript.map名称数组进行排序

时间:2019-03-28 15:41:54

标签: javascript jquery arrays sorting

我正在尝试从此javascript映射中按ABC对名字数组进行排序。 我也想从结果中隐藏“未定义”行:

function contacts_callback(obj) {
    var contactinfo = obj.contacts.map(o => 
        `${o.givenName} ${o.familyName} ${o.organizationName} ${
             o.phoneNumbers.map(n => n.phoneNumber)
        }`)
        .join("<br>");
    document.getElementById("demo").innerHTML = contactinfo;
}

// Demo
var obj = 
  {"success":true,"contacts":[
{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"GGG","organizationName":"","familyName":"ggg",},
{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"AAA","organizationName":"","familyName":"aaa",},
{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"BBB","organizationName":"Apple","familyName":"bbb",},
{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"undefined","organizationName":"","familyName":"",},
{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"","organizationName":"Apple","familyName":"",},
]};

contacts_callback(obj);
<div id="demo"></div>

1 个答案:

答案 0 :(得分:2)

您可以过滤未定义的名称行,并按givenName进行排序,然后映射所需的结果。

function contacts_callback(obj) {
    var contactinfo = obj.contacts
        .filter(({ givenName }) => givenName !== 'undefined')
        .sort(({ givenName: a }, { givenName: b }) => a.localeCompare(b))
        .map(({ givenName, familyName, organizationName, phoneNumbers }) => 
            `${givenName} ${familyName} ${organizationName} ${
                 phoneNumbers.map(({ phoneNumber }) => phoneNumber)
            }`)
        .join("<br>");
    document.getElementById("demo").innerHTML = contactinfo;
}

// Demo
var obj = { success: true, contacts: [{ emailAddresses: [], phoneNumbers: [{ label: "unknown", phoneNumber: "XXX-XXXXXXX" }], givenName: "GGG", organizationName: "", familyName: "ggg" }, { emailAddresses: [], phoneNumbers: [{ label: "unknown", phoneNumber: "XXX-XXXXXXX" }], givenName: "AAA", organizationName: "", familyName: "aaa" }, { emailAddresses: [], phoneNumbers: [{ label: "unknown", phoneNumber: "XXX-XXXXXXX" }], givenName: "BBB", organizationName: "Apple", familyName: "bbb" }, { emailAddresses: [], phoneNumbers: [{ label: "unknown", phoneNumber: "XXX-XXXXXXX" }], givenName: "undefined", organizationName: "", familyName: "" }, { emailAddresses: [], phoneNumbers: [{ label: "unknown", phoneNumber: "XXX-XXXXXXX" }], givenName: "", organizationName: "Apple", familyName: "" }] };

contacts_callback(obj);
<div id="demo"></div>