JSFiddle - React, Tailwind, and code Playground
by jfriend00
HTML
<button id="sortUp">Sort Up</button><button id="sortDown">Sort Down</button><br>
<div id="productList">
<div class="row"><div class="productName">Popcorn</div><div class="price">$5.00</div></div>
<div class="row"><div class="productName">Peanuts</div><div class="price">$4.00</div></div>
<div class="row"><div class="productName">Cookie</div><div class="price">$3.00</div></div>
<div class="row"><div class="productName">Beer</div><div class="price">$5.50</div></div>
<div class="row"><div class="productName">Soda</div><div class="price">$4.50</div></div>
</div>
CSS
.productName {float: left; width: 100px; font-size: 14px;}
.price {font-family: "Courier New"; font-size: 14px;}
.row {clear: both;}
button {margin: 10px 20px 10px 0;}
JavaScript
$("#sortUp").click(function() {
sortPrices("productList", "up");
});
$("#sortDown").click(function() {
sortPrices("productList", "down");
});
function sortPrices(id, direction) {
var prices = [];
$("#" + id + " .price").each(function(index) {
var str = $(this).text();
var item = {};
var matches = str.match(/\d+\.\d+/);
if (matches && matches.length > 0) {
item.price = parseFloat(matches[0]);
item.row = $(this).closest(".row").get(0);
item.index = index;
prices.push(item);
}
});
// now the prices array has all the prices in it
// sort it based on direction
// because of the way we re-insert in the DOM,
// we actually sort the opposite of what we want the final result to be
var fn;
if (direction == "down") {
fn = function(a, b) {return(a.price - b.price);}
} else {
fn = function(a, b) {return(b.price - a.price);}
}
prices.sort(fn);
// now pull each row out and put it at the beginning
var productList = $("#" + id);
for (var i = 0; i < prices.length; i++) {
var self = $(prices[i].row);
self.detach();
productList.prepend(self);
}
}