Skip to content
Advertisement

Jquery sort div based on multiple conditions

I have this short bit of code to sort / ascend div by number. But I want to add other conditions to sort by. Right now, it’s only sorting it just based on points class. But I want it to also apply conditions on times and combine with points.

Generally these divs sort ascend from large number to low number. If the number is equal, it will show those whose time is less. If the number is equal, it will search to see which times is the lowest. And it will show it First.

$(function(){ 
    var sortedList = $('.contest_entry').toArray().sort(function(lhs, rhs){ 
      return parseInt($(rhs).children("span.points").text(),10) - parseInt($(lhs).children("span.points").text(),10); 
   });
    $("#list").html(sortedList);
});
.contest_entry
{
  padding:10px;
  background: #eee;
  margin:10px 0px;
}

.points
{
  display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

<div id="list">
<div class="contest_entry">
<span class="points">14</span>
<span class="times"> 12:39 </span>
</div> 
<div class="contest_entry">
<span class="points">16</span>
<span class="times"> 09:55 </span>
</div>
<div class="contest_entry">
<span class="points">19</span>
<span class="times"> 17:19 </span>
</div>
<div class="contest_entry">
<span class="points">19</span>
<span class="times"> 17:34 </span>
</div>
<div class="contest_entry">
<span class="points">19</span>
<span class="times"> 17:20 </span>
</div>
</div>

In summary, I want to add multiple conditions to filter or sort the divs.

Advertisement

Answer

Try this code please

$(function(){ 
    var sortedList = $('.contest_entry').toArray().sort(function(lhs, rhs){ 
        var lhsPoints = parseInt($(lhs).find(".child span.points").text(),10);
        var rhsPoints = parseInt($(rhs).find(".child span.points").text(),10);
        if (lhsPoints === rhsPoints) {
            // Compare the "times" class if the "points" class is equal
            return $(lhs).find(".child span.times").text() > $(rhs).find(".child span.times").text() ? 1 : -1;
        } else {
            return rhsPoints - lhsPoints;
        }
    });
    $("#list").html(sortedList);
});
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement