这个问题在这里已有答案:
我想按字母顺序按名字对学生列表进行排序,然后打印出包含名字的列表。
我已尝试使用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": "[email protected]",
"password": "R3K[Iy0+"
},
{
"netid": "tb0986",
"firstName": "Michal",
"lastName": "Aguirre",
"email": "[email protected]",
"password": "2Gk,Lx7M"
},
{
"netid": "cw3337",
"firstName": "Deangelo",
"lastName": "Lane",
"email": "[email protected]",
"password": "lolSIU{/"
},
我需要先按字母顺序对姓氏进行排序,然后按顺序打印出名字和姓氏的列表。例如,使用以前的名称,我想得到一个列表,如:
名称:
Michal Aguirre
瑞安豪威尔
迪恩杰洛巷
使用sort
和localeCompare
进行排序,然后使用map
获取名称:
const arr = [{
"netid": "tc4015",
"firstName": "Ryan",
"lastName": "Howell",
"email": "[email protected]",
"password": "R3K[Iy0+"
},
{
"netid": "tb0986",
"firstName": "Michal",
"lastName": "Aguirre",
"email": "[email protected]",
"password": "2Gk,Lx7M"
},
{
"netid": "cw3337",
"firstName": "Deangelo",
"lastName": "Lane",
"email": "[email protected]",
"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; }