Well, the title says it all. What I am doing is creating a featured product module. The drop down list of sizes is populated using JSON and I am using handlebars to render t
const sort = (arr, p, o = "asc") => arr.sort((a, b) => {
if (o !== "asc")[a, b] = [b, a];
const isNum = typeof b[p] === "number";
return (isNum ? Number(a[p]) - b[p] : String(a[p]).localeCompare(b[p]));
});
$.fn.sortChildren = function(op) {
op = $.extend({
by: "textContent",
order: "asc"
}, op);
return this.each(function() {
const i = $(this).prop("selectedIndex");
$(this).html(sort($(this).children(), op.by, op.order)).prop({selectedIndex: i});
});
};
// 1. example: sorting by value, order "asc" (default)
$("#test_1").sortChildren({by: "value"});
// 2. example: sorting by textContent (default), order "desc"
$("#test_2").sortChildren({order: "desc"});
- z
- -20
- ab
- 100
- 1
- 00
- 10
- Ab
- 0.1