开发者

Sort multidimensional array in JavaScript

开发者 https://www.devze.com 2023-01-10 19:20 出处:网络
I need to sort an array containing arrays in ascending numerical order. The data structure looks like this

I need to sort an array containing arrays in ascending numerical order. The data structure looks like this

array = [[escalation],//integer
         [name],
         [email],
         [blackberry]];

I try to sort the array using this function (sorting by escalation)

fu开发者_C百科nction sortfcn(a,b){
 if(a[0]<b[0]){
    return -1;
 }
 else if(a[0]>b[0]){
    return 1;
 }
 else{
    return 0;
 }
}

But my output still looks incorrect...

0 0 10 12 14 16 18 20 20 8

Any advice on how to fix this?


From the sort output you provided, it looks like JavaScript is reading the array elements as strings. See if parseInt works:

function sortfcn(a,b){
 if(parseInt(a[0])<parseInt(b[0])){
    return -1;
 }
 else if(parseInt(a[0])>parseInt(b[0])){
    return 1;
 }
 else{
    return 0;
 }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消