whitesiroi whitesiroi - 6 months ago 34
jQuery Question

How to sort by two attributes - jQuery

Here is the Fiddle

$(".listitems li").sort(sort_li).appendTo('.listitems');
function sort_li(a, b){
return ($(b).data('position')) < ($(a).data('position')) ? 1 : ($(b).data('position2')) > ($(a).data('position2')) ? 1 : 0;
}


How can I sort it by the first attribute
position
and then by the second
position2


Result I want to get:

Item 24 40549
Item 24 40501
Item 24 40500
Item 3 14801
Item 3 14800
Item 1 90500
Item 0 0
Item 0 0
Item 0 0

Answer

Your code work based on the string comparison instead do subtraction for number based sorting.

$(".listitems li").sort(sort_li).appendTo('.listitems');

function sort_li(a, b) {
  // get the diff of `data-position`
  var diff = $(b).data('position') - $(a).data('position');
  // return the difference if it's not 0
  // else return the difference of `data-position2`
  return diff == 0 ? $(b).data('position2') - $(a).data('position2') : diff;
  // although you can use Logical Short-Circuit Evaluation
  // return $(b).data('position') - $(a).data('position') || $(b).data('position2') - $(a).data('position2');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="listitems">
  <li data-position="24" data-position2="40500">Item 24 40500</li>
  <li data-position="1" data-position2="90500">Item 1 90500</li>
  <li data-position="0" data-position2="0">Item 0 0</li>
  <li data-position="0" data-position2="0">Item 0 0</li>
  <li data-position="0" data-position2="0">Item 0 0</li>
  <li data-position="3" data-position2="14800">Item 3 14800</li>
  <li data-position="3" data-position2="14801">Item 3 14801</li>
  <li data-position="24" data-position2="40501">Item 24 40501</li>
  <li data-position="24" data-position2="40549">Item 24 40549</li>
</ul>

Comments