2016-05-11 42 views
-1

我試圖按照字母順序對書名進行排序,而忽略單詞「the」,如果它是標題中的第一個單詞。我需要用javascript來做,沒有庫。使用javascript sort();在字符串數組上,但忽略「The」

// 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

重複的http://stackoverflow.com/q/34347008/1028949 – Quantastical

回答

0

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