mr.abdo
mr.abdo

Reputation: 485

How can I sort items correctly using js

I searched problems similar to this one, but those didn't solve my problem. I have a bootstrap cards showing items. And i have a filter to order this cards by liked votes, but when I trigger the js function, the sort doesnt works well (looks like it's ordering in a random way) .

html:

 <a class="like badge" onclick="vote('{% url 'like_item' pk=item.pk %}', '.liked_item_{{item.id}}', '.disliked_item_{{item.id}}', '.like_{{item.id}}', '.dislike_{{item.id}}')" href="javascript:void(0)">
        <span class="liked_item_{{item.id}} liked_votes">
          {{ item.count_likes }}
        </span>
      </a>

js:

if(this.name == 'thumbsUp'){
    var thumbsUpOrderedDivs = $divs.sort(function (a, b) {
        return $(a).find('.liked_votes').text() < $(b).find('.liked_votes').text();
    });
    $("#idea-list-group").html(thumbsUpOrderedDivs);
}

Upvotes: 0

Views: 85

Answers (2)

Alen.Toma
Alen.Toma

Reputation: 4870

try parsing the text to numbers

    var thumbsUpOrderedDivs = $(".liked_votes").sort(function (a, b) {
        return  parseInt($(a).text()) - parseInt($(b).text());
    });
    
    $(".badge").html(thumbsUpOrderedDivs);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="like badge">
        <span class="liked_item_{{item.id}} liked_votes">
         5
        </span>
          <span class="liked_item_{{item.id}} liked_votes">
         1
        </span>
        
          <span class="liked_item_{{item.id}} liked_votes">
         3
        </span>
        
          <span class="liked_item_{{item.id}} liked_votes">
         100
        </span>
      </a>

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36584

You should use String.prototype.localeCompare()

localCompare:The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order

if(this.name == 'thumbsUp'){
    var thumbsUpOrderedDivs = $divs.sort(function (a, b) {
        return ($(a).find('.liked_votes').text() + '').localeCompare($(b).find('.liked_votes').text());
    });
    $("#idea-list-group").html(thumbsUpOrderedDivs);
}

Upvotes: 2

Related Questions