如何在忽略文章(a,an,the)的情况下对javascript数组进行排序

How can I sort a javascript array while ignoring articles (A, an, the)?

本文关键字:情况下 javascript 数组 排序 an 文章 the      更新时间:2023-09-26

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

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

您可以使用RegExp在比较器中移动它们。还要注意.sort有副作用

function titleComparator(a, b) {
    var articles = ['a', 'an', 'the'],
        re = new RegExp('^(?:(' + articles.join('|') + ') )(.*)$'), // e.g. /^(?:(foo|bar) )(.*)$/
        replacor = function ($0, $1, $2) {
            return $2 + ', ' + $1;
        };
    a = a.toLowerCase().replace(re, replacor);
    b = b.toLowerCase().replace(re, replacor);
    return a === b ? 0 : a < b ? -1 : 1;
}

并将其付诸实践

var books = [
    'A Wonderful Life', 'The Beginning', 'An Everlasting Tale', 'I go in the middle'
];
var sortedBooks = books.slice().sort(titleComparator); // note slice
// ["The Beginning", "An Everlasting Tale", "I go in the middle", "A Wonderful Life"]
相关文章: