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