Sort list with spaces inside, jQuery
I have a problem with sorting a list with spaces inside.
Example:
<a href="">Sort by name</a>
<a href="">Sort by year</a>
<a href="">Sort by fruit</a>
<ul>
<li>
<span class="name">Carl</span>
<span class="year">1954</span>
<span class="fruit">Apple</span>
</li>
<li>
<span class="name">Ann</span>
<span class="year">1932</span>
<span class="fruit">Banana</span>
</li>
<li>
<span class="name">Joe</span>
<span class="year">1961</span>
<span class="fruit">Pineapple</span>
</li>
</ul>
So, I want to be able to sort by these three โcategoriesโ. Has anyone received an offer?
If we change your markup a bit to better handle links, for example:
<div id="sort">
<a href="#name">Sort by name</a>
<a href="#year">Sort by year</a>
<a href="#fruit">Sort by fruit</a>
</div>
<ul id="things">
You can make an easy way to switch between two ways:
$("#sort a").click(function(e) {
var desc = $(this).hasClass("asc"),
sort = this.hash.substr(1),
list = $("#things");
list.append(list.children().get().sort(function(a, b) {
var aProp = $(a).find("span."+sort).text(),
bProp = $(b).find("span."+sort).text();
return (aProp > bProp ? 1 : aProp < bProp ? -1 : 0) * (desc ? -1 : 1);
}));
$(this).toggleClass("desc", desc)
.toggleClass("asc", !desc)
.siblings().removeClass("asc desc");
e.preventDefault();
});
You can check it here , there are other approaches, of course (and the above can be reduced further) ... my main thing here was to demonstrate with the help Array.sort()you can do pretty quick work.
Here is a breakdown of what came out above:
, , , ... , DOM ( ).
, ( ), <span>, .text(), :
$("#sort a").click(function(e) {
var desc = $(this).hasClass("asc"),
sort = this.hash.substr(1),
list = $("#things");
$(list.children().detach().find("span."+sort).get().sort(function(a, b) {
var aProp = $.text([a]),
bProp = $.text([b]);
return (aProp > bProp ? 1 : aProp < bProp ? -1 : 0) * (desc ? -1 : 1);
})).parent().appendTo(list);
$(this).toggleClass("desc", desc)
.toggleClass("asc", !desc)
.siblings().removeClass("asc desc");
e.preventDefault();
});