yarek yarek - 5 months ago 19
jQuery Question

jquery: How to sorti divs by data: getting bad results

I want to sort that by usernames:

<div id="listPerformers">
<div class="performer" data-username="lula">lula</div>
<div class="performer" data-username="hotesse1">hotesse1 </div>
<div class="performer" data-username="marina">marina</div>
<div class="performer" data-username="sabrina">sabrina</div>
<div class="performer" data-username="aaa">aaa</div>
<div class="performer" data-username="hotesse2" >hotesse2 </div>
<div class="performer" data-username="julia">julia</div>
<div class="performer" data-username="misssexy">misssexy</div>
<div class="performer" data-username="guitarreblack">guitarreblack</div>
<div class="performer" data-username="blacklove">blacklove</div>
<div class="performer" data-username="ddd">ddd</div>
<div class="performer" data-username="eee">eee</div>
<div class="performer" data-username="anna">anna</div>
</div>


And I do use that jscript

$('.performer').sort(function(a,b){
return a.dataset.username > b.dataset.username
}).appendTo('#listPerformers')


http://jsfiddle.net/ore0zqxt/

Problem is: it is badly sorted:

julia

anna

comes in first positions !

Answer

Your sort function is not correct. You need to return positive, negative or zero value from compare function in case of greater than, less than or equal.

$('.performer').sort(function(a,b){
    if(a.dataset.username < b.dataset.username) return -1;
    if(a.dataset.username > b.dataset.username) return 1;
    return 0;
}).appendTo('#listPerformers');