0

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]
}

1 Answer 1

2

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)

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.