使用javascript sort();在字符串数组上,但忽略;";

使用javascript sort();在字符串数组上,但忽略;";,javascript,arrays,sorting,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 Catche

我试图按字母顺序对一系列书名进行排序,而忽略“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"]

javascript中的sort函数接受一个比较函数,每个要比较的项都作为参数。在这个函数中,您可以找到并用空字符串替换“The”

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 
});
副本