-6

I have a array in javascript which looks like

var data_tab = [[1,id_1001],[4,id_1004],[3,id_1003],[2,id_1002],[5,id_1005]]

And I want to sort them based on first value like..

1,id_1001

2,id_1002

3,id_1003

4,id_1004

5,id_1005

Is there any way?I can sort them in javascript..

Community
  • 1
  • 1
vinay
  • 105
  • 1
  • 1
  • 12

5 Answers5

2

Array.prototype.sort():

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is lexicographic (not numeric).

CD..
  • 72,281
  • 25
  • 154
  • 163
1

Try:

data_tab.sort(function(a, b){ return a[0] - b[0] })

DEMO:

var data_tab = [[1,'id_1001'],[4,'id_1004'],[3,'id_1003'],[2,'id_1002'],[5,'id_1005']]
data_tab = data_tab.sort(function(a, b){ return a[0] - b[0] })
console.log(data_tab);

# Give [[1,'id_1001'],[2,'id_1002'],[3,'id_1003'],[4,'id_1004'],[5,'id_1005']]
Dhanu Gurung
  • 8,480
  • 10
  • 47
  • 60
1
console.log(data_tab.sort(function(first, second) {
    return first[0] - second[0];
}));

Output

[ [ 1, 'id_1001' ],
  [ 2, 'id_1002' ],
  [ 3, 'id_1003' ],
  [ 4, 'id_1004' ],
  [ 5, 'id_1005' ] ]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1
var data_tab = [[1,"id_1001"],[4,"id_1004"],[3,"id_1003"],[2,"id_1002"],[5,"id_1005"]]

function compare(first,second) {
  if (first[0] < second[0])
     return -1;
  if (first[0] > second[0])
    return 1;
  return 0;
}

data_tab.sort(compare);
Vova Bilyachat
  • 18,765
  • 4
  • 55
  • 80
0
 data_tab.sort(function(a,b){return a[0]-b[0];});
kubari
  • 36
  • 2