I’d like to sort by time,day.
Here is my attempt:
var days = new Array();
var days['SU'] = 0;
var days['MO'] = 1;
var days['TU'] = 2;
var days['WE'] = 3;
var days['TH'] = 4;
var days['FR'] = 5;
var days['SA'] = 6;
events.sort(function(a, b)
{
if(a['day'] != b['day'])
{
return (days[a['day']] < days[b['day']]) ? 1 : -1;
}
else if(a['time'] != b['time'])
{
return (a['time'] < a['time']) ? 1 : -1;
}
else
return 0;
);
It’s not tested, but am I doing it correct?
(Time asc, days asc) Mon 8am, Tues 8am, Mon 9pm is the order I’m looking for.
Cheers.
events[0]['day'] = 'MO';
events[0]['time'] = 8;
events[1]['day'] = 'MO';
events[1]['time'] = 21;
events[2]['day'] = 'TU';
events[2]['time'] = 8;
My solution which seems to work thanks to @T.J. Crowder
events = new Array();
events[0] = new Array();
events[0]['day'] = 'MO';
events[0]['time'] = 8;
events[1] = new Array();
events[1]['day'] = 'MO';
events[1]['time'] = 21;
events[2] = new Array();
events[2]['day'] = 'TU';
events[2]['time'] = 8;
var days = {
'SU': 0,
'MO': 1,
'TU': 2,
'WE': 3,
'TH': 4,
'FR': 5,
'SA': 6
};
events.sort(function(a, b)
{
if (a.time != b.time)
{
return a.time - b.time;
}
else if (a.day != b.day)
{
return days[a.day] - days[b.day];
}
else
{
return 0;
}
});
Condensed:
events.sort(function(a, b)
{
return a.time != b.time
? a.time - b.time
: days[a.day] - days[b.day];
});
Your fundamental approach is sound. A few notes:
You’re not using
daysas an array, so I wouldn’t make it an array. Instead:Also, you don’t need those quotes since none of those strings is a keyword, so:
…but you may choose to keep them as a style thing, or to defend against adding ones that are keywords later.
You don’t have to use the bracketed notation to look up a property (
a['day']) unless the string you’re using for the property name is dynamic or the property name is a reserved word.dayis neither, so you can use the simpler dotted notation (a.day).There is no
elseifin JavaScript; useelse if.You can simplify this:
to
..and you may be able to do something similar with your
timevalues, butI don’t know what they are, so…now that you’ve posted them, I do, and you can.Strongly recommend always using braces, not just when you “need” them. (None of your three branches actually needs them, but you’re only using them on two.)
You’ve compared
a['time']toa['time]rather thanb['time']when checking for equality.You haven’t ended your function (missing
})Since you can just subtract your
timevalues, you don’t need your final equality check.So:
…or you can condense it further:
Live example