I created an array called moonwalkers
and developed a function named alphabetizer
to organize the names in alphabetical order with the last name appearing first.
Although it functions correctly, I am seeking ways to enhance the code.
For my reference, I used an interesting article from Hubrik and consulted Stack Overflow in order to understand how sorting works in JavaScript.
While attempting to modify the compare
function and transform it into the last name
variable, I encountered some difficulties. It seems that my struggle stems from the complexities of 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));