我有一個對象結果集。它具有以下記錄如何根據JavaScript中的對象值對數組進行排序?
var resultset = [{0: "A", 1: "25.14", 2: "0,0,0,0,30.79,0,7.68,0,0,6.13,0,0"},
{0: "B", 1: "3.26", 2: "0,0,0,31,0,0,0,0,0,0,0,0"},
{0: "C", 1: "37.01", 2: "0,0,0,0,0,0,0,0,0,0,0,0"},
{0: "D", 1: "1.18", 2: "0,0,0,9.63,0,0,0,0,0,0,0,0"},
{0: "E", 1: "0.28", 2: "0,0,0,13.22,0,0,0,0,0,0,0,0"}]
我使用了基於價值這個對象進行排序,即指數1通過使用下面的代碼,
resultset.sort(compareSecondColumn);
function compareSecondColumn(a, b) {
//alert("A Value -->"+a[1]);
//alert("B Value -->"+b[1]);
if (a[1] == b[1]) {
return 0;
}
else {
//alert(b[1]);
return (a[1] > b[1]) ? -1 : 1;
}
}
但我無法進行排序基於索引1
我的預期成果是像下面來分類的基礎上指數1(37.01)
{0: "C", 1: "37.01", 2: "0,0,0,0,0,0,0,0,0,0,0,0"}
{0: "A", 1: "25.14", 2: "0,0,0,0,30.79,0,7.68,0,0,6.13,0,0"}
{0: "B", 1: "3.26", 2: "0,0,0,31,0,0,0,0,0,0,0,0"}
{0: "D", 1: "1.18", 2: "0,0,0,9.63,0,0,0,0,0,0,0,0"}
{0: "E", 1: "0.28", 2: "0,0,0,13.22,0,0,0,0,0,0,0,0"}
我試着做一些對象從URL下面的排序機制。但不會爲我工作。
http://www.javascriptkit.com/javatutors/arraysort2.shtml
Sorting JavaScript Object by property value
@Tushar包括我預期的輸出,你可以得到我的問題嗎? – Dhinakar
鑑於您正在排序的字段是以%字符結尾的字符串,您的排序函數需要將值轉換爲數字排序的數字。使用parseFloat(),它會自動忽略%。 – nnnnnn
@nnnnnn我可以將其轉換爲數字。這不是一個問題。即使我改變我也無法做到這一點。這是我的問題。 :( – Dhinakar