我有一个对象结果集。它有以下记录
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做一些对象排序机制。但是不会为我工作。
答案 0 :(得分:4)
你不能对字符串进行排序,只需解析为float然后比较
function compareSecondColumn(a, b) {
var valueA = parseFloat(a[1]);
var valueB = parseFloat(b[1]);
if (valueA == valueB) {
return 0;
} else {
return (valueA > valueB) ? -1 : 1;
}
}
答案 1 :(得分:3)
您正试图在那里对字符串进行排序。
您应该解析该值,并按照
进行操作resultset.sort(function(a, b){
return parseFloat(b[1]) - parseFloat(a[1]);
});