简体   繁体   中英

Javascript custom sort with blanks

I am using the following code to sort a 2d array by column1 with a custom sort order, blanks naturally process as undefined and this is causing a problem when the array contains a series of blank rows. I would like undefined to basically behave as if it equaled 4 for the purpose of my sorting. I'm wondering if I should implement some sort of switch statement to handle this situation but want to retain speed and code brevity.

  var sortBy = {  
    "Order": 0,
    "This": 1,
    "Way": 2,
    "Please": 3,
  };

 values.sort(function(a, b){  
   return sortBy[[a[0]][0]] - sortBy[[b[0]][0]];
  });

The following modification greatly increases loading times, but maybe someone else can provide a more visually efficient solution.

values.sort(function(a, b){  
   var current = typeof sortBy[[a[0]][0]] == 'undefined'?4:sortBy[[a[0]][0]];
   var next = typeof sortBy[[b[0]][0]] == 'undefined'?4:sortBy[[b[0]][0]];
   return current-next;
  });   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM