使用javascript sort();在一个字符串数组,但忽略“的”

时间:2016-05-11 22:01:50

标签: javascript arrays sorting

我试图按字母顺序排列一系列书名,而忽略单词“the”如果它是标题中的第一个单词。我需要使用javascript,没有库。

// Sample Array
var books = ['Moby Dick', 'Hamlet', 'The Odyssey', 'The Great Gatsby', 'The Brothers Karamazov', 'The Iliad', 'Crime and Punishment', 'Pride and Prejudice', 'The Catcher in the Rye', 'Heart of Darkness'];

现在如果我跑:

console.log(books.sort());

它会回来:

["Crime and Punishment", "Hamlet", "Heart of Darkness", "Moby Dick", "Pride and Prejudice", "The Brothers Karamazov", "The Catcher in the Rye", "The Great Gatsby", "The Iliad", "The Odyssey"]

但是,如果标题以“The”开头,我想知道如何在忽略前三个字母的情况下排序,以便它返回:

["The Brothers Karamazov", "The Catcher in the Rye", "Crime and Punishment", "The Great Gatsby", "Hamlet", "Heart of Darkness", "The Iliad", "Moby Dick", "The Odyssey", "Pride and Prejudice"]

1 个答案:

答案 0 :(得分:0)

javascript中的sort函数接受一个比较函数,每个项目都要作为参数进行比较。在此功能中,您可以找到并替换""用空字符串。

books.sort(function(a, b) { 
   // Return 1 left hand side (a) is greater, -1 if not greater.
   return a.replace(/^The /, "") > b.replace(/^The /, "") ? 1 : -1 
});