Abhi Abhi - 4 months ago 23
Javascript Question

JS Sort By Multiple constraints

I have a array of elements as follows:

var a = [
<tr data-order=​"0" data-time=​"840">​…​</tr>​,
<tr data-order=​"0" data-time=​"60">​…​</tr>​,
<tr data-order=​"1" data-time=​"10">​…​</tr>​,
<tr data-order=​"2" data-time=​"20">​…​</tr>​,
<tr data-order=​"3" data-time=​"15">​…​</tr>​,
<tr data-order=​"4" data-time=​"40">​…​</tr>​,
<tr data-order=​"5" data-time=​"30">​…​</tr>​,
<tr data-order=​"6" data-time=​"1320">​…​</tr>​

I want to sort them according to data-order as well as data-time. What I'm able to achieve is:

a.sort(function(m, n) {
return parseInt( $(m).attr("data-order") ) - parseInt( $(n).attr("data-order") )

That gives me elements sorted by date-order, but for same date order, I want it to be sorted by date-time.

How can I sort by multiple attributes?


In case the difference is zero( i.e, values are same) do the second comparison. You can use logical OR (||) for reduce the number of lines. For getting data-* attribute use data() method and there is no need to parse it since we are taking the difference.

a.sort(function(m, n) {
  return $(m).data('order') - $(n).data('order') || $(m).data('time') - $(n).data('time');

Refer : What does the construct x = x || y mean?