I’m using this very handy plugin to sort elements. But comparing elements on a numerical value is producing an incorrect result: 99, 98, 9, 83, 8, 78, etc..
Would this be a problem of the plugin or the way I implemented it?
Code:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script language="javascript">
jQuery.fn.sortElements = (function(){
var sort = [].sort;
return function(comparator, getSortable) {
getSortable = getSortable || function(){return this;};
var placements = this.map(function(){
var sortElement = getSortable.call(this),
parentNode = sortElement.parentNode,
nextSibling = parentNode.insertBefore(
document.createTextNode(''),
sortElement.nextSibling
);
return function() {
if (parentNode === this) {
throw new Error(
"You can't sort elements if any one is a descendant of another."
);
}
parentNode.insertBefore(this, nextSibling);
parentNode.removeChild(nextSibling);
};
});
return sort.call(this, comparator).each(function(i){
placements[i].call(getSortable.call(this));
});
};
})();
$(document).ready(function(){
$('.item').sortElements(function(a,b){
return $(a).html() < $(b).html() ? 1 : -1;
});
});
</script>
</head>
<body>
<% for i = 0 to 100 %>
<div class="item"><%=i*Rnd%></div>
<% next %>
</body>
</html>
If you want to do a sort based on the numeric values of strings, then convert the strings to numbers with the
parseIntMDN docs method(or
parseFloatMDN docs for floating point numbers, as Gaurav mentioned in the comments..)