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 >
<span >14</span>
<span > 12:39 </span>
</div>
<div >
<span >16</span>
<span > 09:55 </span>
</div>
<div >
<span >19</span>
<span > 17:19 </span>
</div>
<div >
<span >19</span>
<span > 17:34 </span>
</div>
<div >
<span >19</span>
<span > 17:20 </span>
</div>
</div>
In summary, I want to add multiple conditions to filter or sort the divs.
CodePudding user response:
I updated you javascript function to compare times if points are equal
$(function(){
var sortedList = $('.contest_entry').toArray().sort(function(lhs, rhs){
var lhsPoints = parseInt($(lhs).children("span.points").text(),10);
var rhsPoints = parseInt($(rhs).children("span.points").text(),10);
var lhsTime = $(lhs).children("span.times").text();
var rhsTime = $(rhs).children("span.times").text();
if (lhsPoints !== rhsPoints) {
return rhsPoints - lhsPoints;
} else {
// Compare times if points are equal
if (lhsTime < rhsTime) {
return -1;
} else if (lhsTime > rhsTime) {
return 1;
} else {
return 0;
}
}
});
$("#list").html(sortedList);
});
.contest_entry {
padding: 10px;
background: #eee;
margin: 10px 0px;
}
.points {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div id="list">
<div >
<span >14</span>
<span >12:39</span>
</div>
<div >
<span >16</span>
<span >09:55</span>
</div>
<div >
<span >19</span>
<span >17:19</span>
</div>
<div >
<span >19</span>
<span >17:34</span>
</div>
<div >
<span >19</span>
<span >17:20</span>
</div>
</div>
CodePudding user response:
Try this script please
$(function(){
var sortedList = $('.contest_entry').toArray().sort(function(lhs, rhs){
var lhsPoints = parseInt($(lhs).children("span.points").text(),10);
var rhsPoints = parseInt($(rhs).children("span.points").text(),10);
if (lhsPoints === rhsPoints) {
// Compare the "times" class if the "points" class is equal
return $(lhs).children("span.times").text() > $(rhs).children("span.times").text() ? 1 : -1;
} else {
return rhsPoints - lhsPoints;
}
});
$("#list").html(sortedList);
});