I have an array moonwalkersand wrote a function alphabetizerto sort the names in alphabetical order and first format them with the last name.
It works great, but how do I write code better?
I used this article from a Hubrik article and referenced Stack Overflow to understand how sorting works in JS.
I tried to rework the function comparein a variable last nameand made a mess. I suspect this is because I'm still trying to raise my head around areas and climbs.
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) {
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);
for (i = 0; i < names.length; i++) {
var lastName = names[i].split(" ")[1];
var firstName = names[i].split(" ")[0];
var newName = lastName + ", " + firstName;
finalNameList.push(newName);
}
return finalNameList;
}
console.log(alphabetizer(moonWalkers));
Run codeHide result
source
share