Reputation: 23
I have this part of function to sort elements by a number. This number is taken from a data-ranking
attribute of the element to sort:
$(".tab_entry").sort(function(a,b){
return parseFloat(a.dataset.ranking) < parseFloat(b.dataset.ranking)
}).appendTo('div.active');
Now the problem: This works perfectly on Firefox 24 but not in Chrome 28 (Sort fails, order got wrong), and does nothing on Safari 5.1.7 and IE 10.
Have anyone get a solution ?
Upvotes: 0
Views: 1324
Reputation: 43728
Try with:
return parseFloat(a.dataset.ranking) - parseFloat(b.dataset.ranking);
This will return a negative number if a
is smaller than b
, which will place a
before b
and vice-versa. If both values are equal, it will return 0
and the order will remain the same since the sort is unstable.
Upvotes: 0
Reputation: 575
jQuery doesn't have a sort function listed in it's API.
You may need to convert your elements to an array first, so you can use the browser's native sort function:
var sortedArray = $(".tab_entry").toArray().sort(function(a,b){ ... })
Furthermore (and perhaps more importantly), the sort function should return a number, not just true/false: Array.prototype.sort
function(a,b) {
//Return the difference in the rankings.
//May need to switch the terms depending on what ordering you want.
return parseFloat(a.dataset.ranking) - parseFloat(b.dataset.ranking)
}
Upvotes: 1