Akhi
Akhi

Reputation: 185

Sort divs by multiple data attributes

How can I sort by both of the data attributes? First I need to sort by discount and then sort by weight.

<div id="list">
    <div class="row" data-weight="1" data-discount=0>banana</div>
    <div class="row" data-weight="3" data-discount=30>apple</div>
    <div class="row" data-weight="4" data-discount=0>avocado</div>
    <div class="row" data-weight="8" data-discount=15>milk</div>
</div>
function sortOrder() {
  divList.sort(function(a, b) { 
    return $(b).data("order")-$(a).data("order");
  });
  $(".list").html(divList);
}

Upvotes: 0

Views: 664

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337580

Your current sort() logic shows how to do this for a single attribute. For multiple attributes you simply need to amend the logic to cater for cases where the values are the same, which can be seen below.

Note that this logic can be made less verbose, but I left it this way to make the flow more obvious.

var $divList = $('#list .row');

function sortOrder() {
  $divList.sort(function(a, b) {
    var $a = $(a), $b = $(b);
    
    if ($a.data('discount') < $b.data('discount')) {
      return 1;
    } else if ($a.data('discount') > $b.data('discount')) {
      return -1;
    }
    
    if ($a.data('weight') < $b.data('weight')) {
      return 1;
    } else if ($a.data('weight') > $b.data('weight')) {
      return -1;
    }
    
    return 0;
  });

  $("#list").append($divList);
}

sortOrder();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list">
  <div class="row" data-weight="1" data-discount=0>banana</div>
  <div class="row" data-weight="3" data-discount=30>apple</div>
  <div class="row" data-weight="4" data-discount=0>avocado</div>
  <div class="row" data-weight="8" data-discount=15>milk</div>
</div>

Upvotes: 2

Related Questions