dho dho - 3 months ago 14
Javascript Question

How to sort and format last names in an array alphabetically in JavaScript

I have an array

moonwalkers
and wrote a function
alphabetizer
to sort the names in alphabetical order and format them with last name first.

It works fine but how do I write better code?

I used this article by Hubrik and referred to Stack Overflow to understand how sort works in JS.

I tried to rework the
compare
function into the
last name
variable and made a mess of it. I suspect this is because I am still trying to get my head around scopes and hoisting.



var moonWalkers = [
"Neil Armstrong",
"Buzz Aldrin",
"Pete Conrad",
"Alan Bean",
"Alan Shepard",
"Edgar Mitchell",
"David Scott",
"James Irwin",
"John Young",
"Charles Duke",
"Eugene Cernan",
"Harrison Schmitt"
];


var finalNameList = [];

function alphabetizer(names) {

// compare last names
function compare (a, b) {
var aName = a.split(" ");
var bName = b.split(" ");
var aLastName = aName[aName.length - 1];
var bLastName = bName[bName.length - 1];

if (aLastName < bLastName) return -1;
if (aLastName > bLastName) return 1;
return 0;
}

names.sort(compare);

// to format names
for (i = 0; i < names.length; i++) {
var lastName = names[i].split(" ")[1];
var firstName = names[i].split(" ")[0];
var newName = lastName + ", " + firstName;

// push newName to global var finalNameList
finalNameList.push(newName);
}

return finalNameList;
}

console.log(alphabetizer(moonWalkers));




Answer

That method isn't ideal because it is only comparing last names. People with the same last name won't get sorted by their first name.

Try this instead:

var moonWalkers = [
  "Neil Armstrong",
  "Buzz Aldrin",
  "Pete Conrad",
  "Alan Bean",
  "Alan Shepard",
  "Edgar Mitchell",
  "David Scott",
  "James Irwin",
  "John Young",
  "Charles Duke",
  "Eugene Cernan",
  "Harrison Schmitt"
];

function alphabetizer(names) {
    var list = [];

    // format names first
    for (i = 0; i < names.length; i++) {
        var lastName = names[i].split(" ")[1];
        var firstName = names[i].split(" ")[0];
        var newName = lastName + ", " + firstName;
        
        //  push newName to global var finalNameList
        list.push(newName);
    }

    // compare entire name
    return list.sort();
}

console.log(alphabetizer(moonWalkers));

Comments