In this sort function I want to be able to re-arrange each .item based on the nested [data-sort] value when the corresponding [data-head] value is clicked.
The problem with the current code is that it creates a new list and sorts the results instead of just re-arranging each .item to match the sort criteria.
How do I set up the sort function to re-arrange each .item based on the data-sort values that match the data-head value?
$(".table").on("click", ".btn", function() {
let table = $(this).closest(".table").eq(0);
let rows = table
.find("[data-sort]")
.toArray()
.sort(comparer($(this).index()));
this.asc = !this.asc;
if (!this.asc) {
rows = rows.reverse();
}
for (var i = 0; i < rows.length; i++) {
table.append(rows[i]);
}
});
function comparer(index) {
return function(a, b) {
var valA = getCellValue(a, index),
valB = getCellValue(b, index);
return $.isNumeric(valA) && $.isNumeric(valB) ?
valA - valB :
valA.localeCompare(valB);
};
}
function getCellValue(row, index) {
return $(row).find("[data-sort]").eq(index).text();
}
.list {
display: flex;
flex-direction: column;
}
.item,
.header {
display: flex;
}
.btn {
cursor: pointer;
}
[data-sort] {
border: 1px solid;
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table">
<div class="header">
<div class="btn" data-head='country'>Country</div>
<div class="btn" data-head='price'>Price</div>
</div>
<div>
<div class="list">
<div class="item">
<div data-sort="country">France</div>
<div>Content</div>
<div>Content</div>
<div data-sort="price">$25</div>
</div>
<div class="item">
<div data-sort="country">spain</div>
<div>Content</div>
<div>Content</div>
<div data-sort="price">$25</div>
</div>
<div class="item">
<div data-sort="country">Lebanon</div>
<div>Content</div>
<div>Content</div>
<div data-sort="price">$17</div>
</div>
</div>
</div>
</div>
.item