我有一个数组moonwalkers
并编写了一个函数alphabetizer
来按字母顺序对名称进行排序,并先用姓氏对它们进行格式化。
它工作正常,但我如何编写更好的代码?
我使用了这个article by Hubrik并引用Stack Overflow来理解JS中的排序是如何工作的。
我尝试将compare
函数重新编写到last name
变量中,并弄得一团糟。我怀疑这是因为我仍然试图绕过范围和悬挂。
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));
&#13;
答案 0 :(得分:1)
这种方法并不理想,因为它只是比较姓氏。具有相同姓氏的人不会按名字排序。
请改为尝试:
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));
&#13;
更新:此版本将在结果中包含中间名称或昵称。如果名称包含类似&#34; Jr&#34;的后缀,它将无法按预期工作。或&#34; Esq&#34;。
var moonWalkers = [
"Neil Armstrong",
"Edwin \"Buzz\" Aldrin",
"Charles \"Pete\" Conrad",
"Alan Bean",
"Alan Shepard",
"Edgar Mitchell",
"David Scott",
"James Irwin",
"John Young",
"Charles Duke",
"Eugene Cernan",
"Harrison \"Jack\" Schmitt"
];
function alphabetizer(names) {
return names.map(function(name) {
var full = name.split(" "),
last = full.pop();
return last + ", " + full.join(" ");
}).sort();
}
console.log(alphabetizer(moonWalkers));
&#13;