Order divs alphabetically and place empty divs at the bottom

I alphabetically orders divs by content .instructor

:

var alphabeticallyOrderedDivs = jQuery('.entry').sort(function(a, b) {
    var $aTitle = jQuery(a).find('.instructor'), $bTitle = jQuery(b).find('.instructor');
    return String.prototype.localeCompare.call($aTitle.text().toLowerCase(), $bTitle.text().toLowerCase());
});

      

It works great.

However, if .instructor

empty, it puts an empty div at the top. My question is, how can I add empty ones at the bottom of the list ?

It currently returns:

empty
a
b
c
...

      

Edit

Here is a jsFiddle . Notice how an empty div is added to the top of the alphabetically ordered divs. I want it downstairs.

+3


source to share


2 answers


String.prototype.localeCompare

places the pivot string ( $aTitle

) after the matching string if the method returns a positive value. Therefore, you need to return any positive value to put empty headers:

var alphabeticallyOrderedDivs = $('.entry').sort(function (a, b) {
    var $aTitle = $(a).find('.title'), $bTitle = $(b).find('.title');

    if (!$aTitle.text()) return 1;
    if (!$bTitle.text()) return -1;

    return String.prototype.localeCompare.call($aTitle.text().toLowerCase(), $bTitle.text().toLowerCase());
});

      

This code works like this:

  • If A is empty, put it after B
  • if A is not empty but B is empty, put B after A (return -1)
  • If none of the lines are empty, sort them by value


Here's your updated snippet:

var alphabeticallyOrderedDivs = $('.entry').sort(function (a, b) {
    var $aTitle = $(a).find('.title'), $bTitle = $(b).find('.title');
    
    if (!$aTitle.text()) return 1;
    if (!$bTitle.text()) return -1;
    
    return String.prototype.localeCompare.call($aTitle.text().toLowerCase(), $bTitle.text().toLowerCase());
    });

var container = $(".container");
container.detach().empty().append(alphabeticallyOrderedDivs);
$('body').append(container);
      

.entry {
  border: 1px solid #CCC;
  padding: 5px;
  margin: 5px;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="entry">
    <div class="title">World</div>
  </div>

  <div class="entry">
    <div class="title">hello</div>
  </div>

  <div class="entry">
    <div class="title"></div>
  </div>

  <div class="entry">
    <div class="title">Lorem</div>
  </div>
</div>
      

Run codeHide result


+2


source


Could you do something like this?



var alphabeticallyOrderedDivs = $('.entry').sort(function (a, b) {
    var $aTitle = $(a).find('.title'), $bTitle = $(b).find('.title');
    if ($bTitle.text().length === 0) {
        return -1;
    }

    if ($aTitle.text().length === 0) {
        return 1;
    }
    return String.prototype.localeCompare.call($aTitle.text().toLowerCase(), $bTitle.text().toLowerCase());
});

      

+3


source







All Articles