Home > OS >  Javascript Sort on 2D array
Javascript Sort on 2D array

Time:10-28

I want to sort the data1 by second column. I tried the below code but it seems sorting is not right. If I try with a single dimension array, the results are correct. What am I doing wrong?

function test(){
  var data1 = [['MED1000','ZITHROMAX 15ML'],
              ['MED01188','AZILEB TABLET 500MG'],
              ['MED1212','AGOMET-200MG (METRONIDAZOLE) TABLET']
             ];
  
  data1.sort(function(a, b) {
    return a[1] - b[1];
});
  Logger.log(data1); // this does not produce right results 
// output:  [[MED1000, ZITHROMAX 15ML], [MED01188, AZILEB TABLET 500MG], [MED1212, AGOMET-200MG (METRONIDAZOLE) TABLET]]
  var data2 = ['ZITHROMAX 15ML','AZILEB TABLET 500MG','AGOMET-200MG (METRONIDAZOLE) TABLET'];
  data2.sort();
  Logger.log(data2); // this works
// output : [AGOMET-200MG (METRONIDAZOLE) TABLET, AZILEB TABLET 500MG, ZITHROMAX 15ML]
}

CodePudding user response:

referenced Array.prototype.sort()

data1.sort(function(a, b) {
    return a[1] - b[1];  //This would work if the values are numbers not strings.
});

you need to use <,> operators for strings

 var data1 = [['MED1000','ZITHROMAX 15ML'],
              ['MED01188','AZILEB TABLET 500MG'],
              ['MED1212','AGOMET-200MG (METRONIDAZOLE) TABLET']
             ];
   
data1.sort((a,b) => (a[1] > b[1]) ? 1 : ((b[1] > a[1]) ? -1 : 0))

console.log(data1)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

for numbers your method would work

 var data1 = [['MED1000','ZITHROMAX 15ML',6],
              ['MED01188','AZILEB TABLET 500MG',7],
              ['MED1212','AGOMET-200MG (METRONIDAZOLE) TABLET',3]
             ];
   
  data1.sort(function(a, b) {
    return a[2] - b[2];
  }); 

console.log(data1)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related