javascript - 如何在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"]
解决方案
一种解决方案是使用带有正则表达式的String.match()surname
来从Array.sort()other names
内部拆分。然后您可以使用String.localeCompare()首先比较,如果它们相等则比较. 请注意,在这种方法中,数组上的每个元素至少需要一个和一个,否则它将不起作用。此外,方法Array.slice()仅用于不改变(更改)原始数组的目的,但如果您不介意,可以丢弃它。surnames
other names
first name
surname
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;}
推荐阅读
- sql - SQL联合两个表并将表名保留在一列中
- basic-authentication - 使用 Cro 的 perl6 中的基本身份验证
- angular - Angular:当没有在任何提供者中声明路由器时,如何将路由器注入组件中?
- java - 将字符串拆分为 n 部分,用破折号分隔
- jquery - 仅从 Json 响应中拆分值
- java - 创建实体后的 Spring Hibernate 异常
- php - 单击任何链接后如何重新加载页面
- java - HTTP 状态码总是从 HttpServletResponse 返回 200
- python - heapq.nlargest() 的关键函数
- python - 如何在 Python 中访问我的 iPhone 文件(通过 USB)?