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

时间:2015-12-18 01:06:06

标签: javascript sorting

我有以下排序功能来排序书籍列表:

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

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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

您可以使用 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"]