Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array by custom variables

$("#show_times_available_" + pos).find("td span").parent().each(function(){ 
    array.push($(this).attr("id")); 
    array = array.sort();
});

My array takes all of the elements and grabs their ID and pushes it into an array so my array will end up as;

[ "mon_0600-0", "sun_0700-0", "thu_0600-0", "thu_0700-0", "tue_0300-0", "wed_0700-0" ];

What I'm trying to do is sort those elements as (mon, tue, wed, etc...) every time a new element is pushed into the array. so that my array will end up as;

[ "mon_0600-0", "tue_0300-0", "wed_0700-0", "thu_0600-0", "thu_0700-0", "sun_0700-0" ];

Using the basic sort() function will put it alphabetically and I know that the sort() function can take in another function. I'm just not sure how to set this up in vanilla javascript or jQuery. Is there a CASE THEN or a way to use when() and then() to sort these? I've search all around google and SO but nothing.

like image 210
Dustin Lawrence Avatar asked Mar 14 '23 06:03

Dustin Lawrence


2 Answers

You need to pass a custom function to sort() as you say. In here, you need to split the days from the times, then return the comparison of the day part then the time part (if the days are the same):

var arr = ["mon_0600-0", "sun_0700-0", "thu_0600-0", "thu_0700-0", "tue_0300-0", "wed_0700-0"];

// store the order of the days
var days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];

var arrSorted = arr.sort(function(a, b) {
  // a and b are two times to compare

  // split each into days and times, e.g ["mon", "0600-0"]
  var aSplit = a.split("_");
  var bSplit = b.split("_");
  
  // get the index of the days to compare
  var dayA = days.indexOf(aSplit[0]);
  var dayB = days.indexOf(bSplit[0]);
  
  // if days are the same, compare the times using normal String comparison
  // if days are different, return the comparison of their position in the array
  return dayA == dayB ?
  	aSplit[1].localeCompare(bSplit[1])
  	: dayA - dayB;
});

console.log(arrSorted);
like image 135
Rhumborl Avatar answered Mar 21 '23 03:03

Rhumborl


here you go with a custom sort function

// your array
array = [ "mon_0600-0", "sun_0700-0", "thu_0600-0", "thu_0700-0", "tue_0300-0", "wed_0700-0" ];

// the order stored in an object
daynames={
    mon:1,
    tue:2,
    wed:3,
    thu:4,
    fri:5,
    sat:6,
    sun:7
}

// the custom sort function which gets the value for the dayname-key and compares
function SortByDayName(a, b){

  // get the value of dayname + the time 
  var aName = daynames[a.substr(0,3)] + a.substr(4,7);;
  var bName = daynames[b.substr(0,3)] + b.substr(4,7);; 
  return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}

// apply sort
array.sort(SortByDayName);

// output:
["mon_0600-0", "tue_0300-0", "wed_0700-0", "thu_0600-0", "thu_0700-0", "sun_0700-0"]
like image 32
john Smith Avatar answered Mar 21 '23 03:03

john Smith