0

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);
}
mr.abdo
  • 445
  • 1
  • 5
  • 15
  • [Your sorting function is not symmetric](https://stackoverflow.com/questions/24080785/sorting-in-javascript-shouldnt-returning-a-boolean-be-enough-for-a-comparison) – VLAZ Feb 07 '19 at 13:28
  • Do the curlys `{{ }}` indicate Angular? In which case, or for a similar framework, I would look into a sort or orderBy pipe to do the sorting. – Andy G Feb 07 '19 at 13:35
  • @AndyG it's django – mr.abdo Feb 07 '19 at 14:04
  • Possible duplicate of [Javascript : natural sort of alphanumerical strings](https://stackoverflow.com/questions/2802341/javascript-natural-sort-of-alphanumerical-strings) – Heretic Monkey Feb 07 '19 at 14:12

2 Answers2

2

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);
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
1

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>
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31
  • That is still not a symmetric sorting function and would not guarantee correct sorting. – VLAZ Feb 07 '19 at 13:38