首页 > 解决方案 > 如何在Javascript中先按姓氏排序名称数组,然后按名字和中间名排序

问题描述

我有一组名称,我想先排序last name,然后排序first name,最后排序middle name。可能middle name超过. 1例如,如果我有一个包含名称的数组:

["James Morrison", "Billy Z Joel", "Billy Joel", "Billy A Joel"]

我如何将其排序为:

["Billy Joel", "Billy A Joel", "Billy Z Joel", "James Morrison"]

标签: javascriptarrayssorting

解决方案


一种解决方案是使用带有正则表达式的String.match()surname来从Array.sort()other names内部拆分。然后您可以使用String.localeCompare()首先比较,如果它们相等则比较. 请注意,在这种方法中,数组上的每个元素至少需要一个和一个,否则它将不起作用。此外,方法Array.slice()仅用于不改变(更改)原始数组的目的,但如果您不介意,可以丢弃它。surnamesother namesfirst namesurname

const names = ["James Morrison","Billy Z Joel","Billy Joel","Billy A Joel", "James Junior Joseph Morrison"];

let res = names.slice().sort((a, b) =>
{
    let [aNames, aSurname] = a.match((/(.*)\s(\w+)$/)).slice(1);
    let [bNames, bSurname] = b.match((/(.*)\s(\w+)$/)).slice(1);

    if (aSurname.localeCompare(bSurname))
        return aSurname.localeCompare(bSurname);
    else
        return aNames.localeCompare(bNames);
});

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}


推荐阅读