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

How to sort a list of last names alphabetically using the sort method

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

我已经尝试使用 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{/"
  },

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

姓名:

迈克尔·阿吉雷

瑞恩豪厄尔

迪安吉洛巷

使用sort with localeCompare to sort, then use 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; }