gpt4 book ai didi

javascript - 如何在忽略冠词 (A, an, the) 的同时对 javascript 数组进行排序?

转载 作者:数据小太阳 更新时间:2023-10-29 06:05:46 24 4
gpt4 key购买 nike

我有以下排序函数来对书籍列表进行排序:

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

我如何调整它以便忽略每个标题开头的文章?

最佳答案

您可以简单地使用函数 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);

关于javascript - 如何在忽略冠词 (A, an, the) 的同时对 javascript 数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34347008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com