gpt4 book ai didi

javascript - 如何使用排序方法按字母顺序对姓氏列表进行排序

转载 作者:行者123 更新时间:2023-12-02 23:53:18 24 4
gpt4 key购买 nike

我想按学生姓名的字母顺序对学生列表进行排序,然后打印出包含他们名字的列表。

我尝试了使用 sort() 函数的不同方法,但无法让它工作。

我的代码:

const students = require('./students1.json');
const fs = require('fs');

for (let student of students) {
let NetID = student.netid;

var lastname = student.lastName;
lastname.sort();
let name = student.firstName + " " + student.lastName;
}

我想要排序的示例

{
"netid": "tc4015",
"firstName": "Ryan",
"lastName": "Howell",
"email": "seersucker1910@outlook.com",
"password": "R3K[Iy0+"
},
{
"netid": "tb0986",
"firstName": "Michal",
"lastName": "Aguirre",
"email": "agaty2027@yahoo.com",
"password": "2Gk,Lx7M"
},
{
"netid": "cw3337",
"firstName": "Deangelo",
"lastName": "Lane",
"email": "harpy1986@live.com",
"password": "lolSIU{/"
},

我需要首先按字母顺序对姓氏进行排序,然后按名字和姓氏的顺序打印出列表。例如,对于以前的名称,我想获得如下列表:

姓名:

米哈尔·阿吉雷

瑞恩·豪厄尔

迪安吉洛·莱恩

最佳答案

使用sortlocaleCompare排序,然后使用 map获取名称:

const arr = [{
"netid": "tc4015",
"firstName": "Ryan",
"lastName": "Howell",
"email": "seersucker1910@outlook.com",
"password": "R3K[Iy0+"
},
{
"netid": "tb0986",
"firstName": "Michal",
"lastName": "Aguirre",
"email": "agaty2027@yahoo.com",
"password": "2Gk,Lx7M"
},
{
"netid": "cw3337",
"firstName": "Deangelo",
"lastName": "Lane",
"email": "harpy1986@live.com",
"password": "lolSIU{/"
}
];

const names = arr.sort(({ lastName: a }, { lastName: b }) => a.localeCompare(b)).map(({ firstName, lastName }) => `${firstName} ${lastName}`);

console.log(names);
.as-console-wrapper { max-height: 100% !important; top: auto; }

关于javascript - 如何使用排序方法按字母顺序对姓氏列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55546207/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com