在多维数组中排序失败

时间:2012-07-23 20:23:36

标签: javascript multidimensional-array sorting

我花了很多时间在这上面,但未能在这里发现错误。

基本上,我有一个类型var test_arr = [['79',0],['8',1],['30', 2],['580',3],['59',4]]的多变量数组,我从一个函数生成。它的行为与正常数组不同,因为我的排序fxn var sort_arrays = function(a,b) {return a[0]-b[0]};无法正确排序数组值。

我试图确保我有一个实际的数组,并且我没有调用替代的排序方法。

因此:

console.log(arr_test.sort(sort_arrays)); 

给予:[[8,1],[30,2],[59,4],[79,0],[580,3]]

然而,在我的fxn上调用它,

console.log(input_kde.sort(sort_arrays));

,给出:[...,[580, 0.002],[59,0.001]]

在尝试生成一些可打印的输出时,我在结果上调用了.toString,并得到了正确排序的输出,这只会加剧我的混乱。

我尝试使用parseFloat(a[0])进行显式类型转换无效。

我也试图确认这确实是一个数组:

console.log(typeof(input_kde)); //#> object
console.log(input_kde.constructor); //#> function Array() { [native code] }
console.log(input_kde instanceof Array); //#> true

另外,input_kde [0]是一个数组,而input_kde [0] [0]是一个数字

console.log(input_kde[0] instanceof Array); //#> true
console.log(typeof(input_kde[0][0])); //#> number

我错过了什么?

EDIT2

var input_kde = [[22,0.0017095221275204712],[24,0.001712291003699343],[28,0.001716821328044571],[307,0.0009792081392809542],[33,0.0017205981968323918],[34,0.0017211029300063302],[341,0.0010085669284820244],[35,0.0017215244128879188],[387,0.0010558490092862406],[4,0.0016696065108796395],[40,0.0017223891946762664],[448,0.0010667514507313397],[491,0.0010124434821844265],[519,0.0009480280002363708],[580,0.0007465298453339767],[59,0.0017073128314605394]]

3 个答案:

答案 0 :(得分:0)

我可能只是在黑暗中拍摄,但你有混合类型(字符串和整数)?

答案 1 :(得分:0)

似乎工作正常http://jsfiddle.net/w8T32/

var test_arr = [['79',0],['8',1],['30', 2],['580',3],['59',4]];
test_arr.sort(function(a,b){
    return a[0] -b[0];
});
console.log(test_arr)​

输出类似于

[['8',1], ['30',2], ['59', 4], ['79',0], ['580', 3]]

要考虑的一件事是sort没有记录的返回值(它修改了数组)但你似乎正在使用它。更改您的代码,使其不依赖于返回值,看看是否有任何区别

答案 2 :(得分:0)

var input_kde = [[22,0.0017095221275204712],[24,0.001712291003699343],[28,0.001716821328044571],[307,0.0009792081392809542],[33,0.0017205981968323918],[34,0.0017211029300063302],[341,0.0010085669284820244],[35,0.0017215244128879188],[387,0.0010558490092862406],[4,0.0016696065108796395],[40,0.0017223891946762664],[448,0.0010667514507313397],[491,0.0010124434821844265],[519,0.0009480280002363708],[580,0.0007465298453339767],[59,0.0017073128314605394]]



    //test run
    var sorted=input_kde.sort(function(a,b){return a[0]-b[0]});
    alert(sorted);

我找不到任何错误!!!!

实际上,为什么你的代码在第二次运行中无法返回正确的值是因为你已经将变量sort_arrays设置为前一个!因此,失败了!