Javascript Multidimentional Array Sorting By Numerical Order
I have a two dimensional array that I need to sort numerically. Here is a sample of the array: [0] [1] 3 320 55B 250 26 100 55A 260 56 310
Solution 1:
The parseInt method will ignore any string characters after the number, removing the A's and B's.
arr.sort(function(rowA, rowB){
var a = parseInt(rowA[0], 10);
var b = parseInt(rowB[0], 10);
if (a > b)
return1;
elseif (a < b)
return -1;
return0;
});
Solution 2:
Just for note - if this A and B has nothing to do with sort, than go with parseInt
as Zack posted.
But if it should be used in sort, you can go with something like this:
arr.sort(function(l,r){
var vl = l[0].split(/(\d+)(\D*)/),
vr = r[0].split(/(\d+)(\D*)/);
vl[1] = parseInt(vl[1]);
vr[1] = parseInt(vr[1]);
if(vl[1] < vr[1]){
return -1;
}elseif(vl[1] === vr[1]){
if(vl[2] < vr[2]) return -1;
elseif(vl[2] === vr[2]) return0;
elsereturn1;
}else{
return1;
}
});
Post a Comment for "Javascript Multidimentional Array Sorting By Numerical Order"