2017-05-17 92 views
1

這是我的數組,我試圖對它進行排序。但它沒有按預期工作。我想按降序對名稱進行排序..我該怎麼做?jquery數組排序不按預期工作

var d = '{"success":"1","message":[{"_id":"591b39df358f1d1f843231d1","area":"chennai","food":"idly","name":"saravana bavan","__v":0},{"_id":"591b39e0358f1d1f843231d2","area":"Dindigul","food":"Dosa","name":"Kattu Briyani","__v":0},{"_id":"591b39df358f1d1f843231d4","area":"Tirupur","food":"Poori","name":"French Loaf","__v":0}]}'; 
 
console.log(d); 
 
var results = jQuery.parseJSON(d); 
 
console.log(results.message); 
 
results.message.sort(function(a, b) { 
 
    return b.name- a.name; 
 
}); 
 
console.log(results.message);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

這是我Fiddle

+0

您可以使用SO具有演示'<>' – guradio

+3

如果你想的名字降序排序,那麼你爲什麼排序按面積? – Bergi

+0

@Bergi,抱歉,這是一個錯字,相應地改變它 –

回答

0

你不能對字符串進行數學運算。

results.message.sort(function(a, b) { 
    if (b.name > a.name) { return 1 } 
    else if (b.name < a.name) { return -1 } 
    else { return 0 } 
}); 

由於@bergi在下面的評論中提到。 This深入解釋了這個問題。

+1

只是我或這個答案是從@Bergi給出的鏈接 – guradio

+0

剛剛檢查。它基本上是一樣的東西,但是沒有其他方法可以做到這一點嗎?我將添加鏈接到我的答案。 –

+0

如何返回b.name.localeCompare(a.name)' – Phil

-1

只是改變你的比較功能如下:

var d = '{"success":"1","message":[{"_id":"591b39df358f1d1f843231d1","area":"chennai","food":"idly","name":"saravana bavan","__v":0},{"_id":"591b39e0358f1d1f843231d2","area":"Dindigul","food":"Dosa","name":"Kattu Briyani","__v":0},{"_id":"591b39df358f1d1f843231d4","area":"Tirupur","food":"Poori","name":"French Loaf","__v":0}]}'; 
console.log(d); 
var results = jQuery.parseJSON(d); 
console.log(results.message); 
results.message.sort(function(a, b) { 
    return b.name.toLowerCase() > a.name.toLowerCase() ? 1 : -1; 
}); 
console.log(results.message); 
+0

[不要忘記在適當的時候返回'0'!](http://stackoverflow.com/a/20892652/1048572) – Bergi

+0

@Bergi它應該是更慢的權利?,但我只是好奇,有人有基準嗎? 「交換」與「額外if」陳述相比要慢多少? – am05mhz

+0

正確性受損時,我不關心速度。不返回'0'不適用於排序數組中的重複值。 – Bergi