我具有以下排序功能,可以对书籍清单进行排序:
var compare = function(a, b) { var aTitle = a.title.toLowerCase(), bTitle = b.title.toLowerCase(); if (aTitle > bTitle) return 1; if (aTitle < bTitle) return -1; return 0; }; var sortedBooks = books.sort(compare);
我该如何调整以免忽略每个标题开头的文章?
您可以简单地说一个函数say removeArticles()
,该函数检查句子中是否有多个单词,如果是,则返回第二个单词进行比较。对于具体的话,你只需要添加条件的话,例如(words[0] == 'a' || words[0] == 'the' || words[0] == 'an')
将覆盖"A"
,"An"
和"The"
:
books = ["A Whale", "The Moive", "A Good Time", "The Alphabet 2" , "The Alphabet 1", "Alphabet Soup", "Foo"];
var compare = function(a, b) {
var aTitle = a.toLowerCase(),
bTitle = b.toLowerCase();
aTitle = removeArticles(aTitle);
bTitle = removeArticles(bTitle);
if (aTitle > bTitle) return 1;
if (aTitle < bTitle) return -1;
return 0;
};
function removeArticles(str) {
words = str.split(" ");
if(words.length <= 1) return str;
if( words[0] == 'a' || words[0] == 'the' || words[0] == 'an' )
return words.splice(1).join(" ");
return str;
}
var sortedBooks = books.sort(compare);
// [ "The Alphabet 1", "The Alphabet 2", "Alphabet Soup", "Foo", "A Good Time", "The Moive", "A Whale" ]
console.log(sortedBooks);