Search code examples
javascriptsortingfsalphabetical

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


I want to sort a list of students by their names alphabetically then print out that list with their first names included.

I have tried different methods with the sort() function but I cannot get it to work.

My Code:

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;
}

An example of what I want to sort

{
    "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{/"
  },

I need to first sort the last names alphabetically then print out the list with first and last name in that order. For example, with the previous names I want to get a list like:

Names:

Michal Aguirre

Ryan Howell

Deangelo Lane


Solution

  • Use sort with localeCompare to sort, then use map to get the names:

    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; }