如何在忽略文章(A,An,the)的同时对javascript数组进行排序? [英] How can I sort a javascript array while ignoring articles (A, an, the)?

查看:83
本文介绍了如何在忽略文章(A,An,the)的同时对javascript数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下排序功能,可以对书籍列表进行排序:

I have the following sort function to sort a list of books:

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

如何进行调整,以使我忽略每个标题开头的文章?

How can I adjust this such that I ignore articles at the beginning of each title?

推荐答案

您可以简单地使用一个名为removeArticles()的函数,该函数检查句子中是否有多个单词,如果是,则返回第二个单词进行比较.仅对于特定单词,您需要为单词添加条件,例如(words[0] == 'a' || words[0] == 'the' || words[0] == 'an')会覆盖"A""An""The":

You can simply have a function say removeArticles() which checks if there is more than a single word in the sentence, if so return the second word for comparison. For specific words only you would need to add conditions for the words, for example (words[0] == 'a' || words[0] == 'the' || words[0] == 'an') would cover "A", "An", and "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);

这篇关于如何在忽略文章(A,An,the)的同时对javascript数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆