我想按字母顺序对学生名单进行排序,然后打印出包括名字在内的名单。
我已经尝试过使用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{/"
},
我需要先按字母顺序对姓进行排序,然后按该顺序打印出姓和名的列表。 例如,使用以前的名字,我想得到一个像这样的列表:
名称:
米歇尔·阿奎尔
Ryan Howell
迪安吉洛巷
答案 0 :(得分:1)
使用sort
和localeCompare
进行排序,然后使用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; }