Reputation: 2923
I am using following code to sort items based on their numbers, but it sort them wrongly.
$('#number').on('click', function() {
var s = $(this).data('sort');
console.log(s);
if (s === 1) {
$(this).data('sort', 0);
$('.mylist > div').sort(function(a, b) {
return a.dataset.sid > b.dataset.sid
}).appendTo('.mylist')
} else {
$(this).data('sort', 1);
$('.mylist > div').sort(function(a, b) {
var temp = a.dataset.sid + " < " + b.dataset.sid
console.log(temp);
return a.dataset.sid < b.dataset.sid
}).appendTo('.mylist')
}
});
The values are in following order by default, 10000,1500,8900,0,0
When I click once it will be 8900 1500 10000 0 0
If I click again they will be 0 0 10000 1500 8900
The console is as following:
10000 < 1500
10000 < 8900
1500 < 8900
0 < 0
10000 < 0
0 < 0
0 < 10000
1500 < 8900
0 < 8900
10000 < 8900
10000 < 1500
Upvotes: 0
Views: 49
Reputation: 9100
Try this:
$('.mylist > div').sort(function(a, b) {
return Number(a.dataset.sid) > Number(b.dataset.sid)
}).appendTo('.mylist')
It seems you are sorting by strings, but you would like to sort by numbers.
Upvotes: 1