yarek yarek - 1 year ago 90
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>

And I do use that jscript

return a.dataset.username > b.dataset.username


Problem is: it is badly sorted:



comes in first positions !

Answer Source

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.

    if(a.dataset.username < b.dataset.username) return -1;
    if(a.dataset.username > b.dataset.username) return 1;
    return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download