Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Array Sort with Dynamic Column [duplicate]

I have some code using JavaScript Array Sorting that works but seems to be really inefficient.

I have an array of objects defined as follows for example purposes

dummyData = [];
dummyData.push({ col01:"aa", col02:"ac", col03:"ab" });
dummyData.push({ col01:"ab", col02:"ab", col03:"ac" });
dummyData.push({ col01:"ac", col02:"aa", col03:"aa" });

Which I can then sort on col01 using a function like this

function f_sort_col01(dataArg) {

   dataArg.sort(function(res01, res02) {
      var arg01 = res01.col01.toLowerCase();
      var arg02 = res02.col01.toLowerCase();
      if(arg01 < arg02) { return -1; }
      if(arg01 > arg02) { return 1; }
      return 0;
   });

   return dataArg;

}

This works just fine but the problem is that when I need to sort on a different column I then have to create an entire new function like this

function f_sort_col02(dataArg) {

   dataArg.sort(function(res01, res02) {
      var arg01 = res01.col02.toLowerCase();
      var arg02 = res02.col02.toLowerCase();
      if(arg01 < arg02) { return -1; }
      if(arg01 > arg02) { return 1; }
      return 0;
   });

   return dataArg;

}

Which is pretty much the same thing only on a different column. I was wondering if it's possible to do something along the lines of this

function f_sort(dataArg, colName) {

   dataArg.sort(function(res01, res02) {
      var arg01 = res01.colName.toLowerCase();
      var arg02 = res02.colName.toLowerCase();
      if(arg01 < arg02) { return -1; }
      if(arg01 > arg02) { return 1; }
      return 0;
   });

   return dataArg;

}

So that the name of the column can be included in the parameters

like image 795
TheLovelySausage Avatar asked Dec 13 '22 11:12

TheLovelySausage


1 Answers

Use square brackets like following

function f_sort(dataArg, colName) {

   dataArg.sort(function(res01, res02) {
      var arg01 = res01[colName].toLowerCase();
      var arg02 = res02[colName].toLowerCase();
      if(arg01 < arg02) { return -1; }
      if(arg01 > arg02) { return 1; }
      return 0;
   });
   return dataArg;
}
like image 160
Nikhil Aggarwal Avatar answered Dec 21 '22 12:12

Nikhil Aggarwal