Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort jQuery list by two attributes

Tags:

jquery

I've this markup:

#a(data-row="2", data-col="3") a
#b(data-row="1", data-col="1") b
#c(data-row="1", data-col="3") c
#d(data-row="2", data-col="2") d
#e(data-row="1", data-col="2") e
#f(data-row="2", data-col="1") f

As you can see, it defines a grid of elements (3 columns and 2 rows).

I need to get this list of items with jQuery and order them by row and by col.

The result of the markup provided should be:

b, e, c, f, d, a

I can successfully order them by row but then I don't know what is the best way to order them by col:

var gridElements = $('div');
gridElements.sort(function (a, b) {
  var contentA =parseInt( $(a).attr('data-row'));
  var contentB =parseInt( $(b).attr('data-row'));
  return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
});

CodePen: http://codepen.io/FezVrasta/pen/bVEezw

I think I should filter the list by data-row and then run sort again on each group, but how?

like image 981
Fez Vrasta Avatar asked Mar 14 '23 19:03

Fez Vrasta


1 Answers

The second value is only applicible if the first values are equal, so this should do it for you:

var gridElements = $('div');
gridElements.sort(function (a, b) {
  var contentA =parseInt( $(a).attr('data-row'));
  var contentB =parseInt( $(b).attr('data-row'));


  //check if the rows are equal
  if (contentA === contentB) {
     var colA = parseInt( $(a).attr('data-col'));
     var colB = parseInt( $(b).attr('data-col'));

     //do the same as your already doing but using different data, from above
     return (colA < colB) ? -1 : (colA > colB) ? 1 : 0;
  }
  else {
    return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
  }
});
like image 162
Liam Avatar answered May 19 '23 23:05

Liam