Alphabetically Order HTML List with Headers

I am looking to Alphabetically order an HTML list, but after each letter, there would be a <hr /> tag and a header, indicating the new letter list.

To revise if I wasn’t clear enough, I have my list…

<ul>
  <li><a href="#/"> john-smith/</a></li>
  <li><a href="#/"> joe-smith/</a></li>
  <li><a href="#/"> glen-smith/</a></li>
  <li><a href="#/"> daniel-smith/</a></li>
  <li><a href="#/"> johnny-smith/</a></li>
</ul>

And now, I wanted to have some JS code that would organise this list alphabetically, as well as give a header & line for each new letter; thus it would give an outcome somewhat similar to:

<ul>
  <hr />
  <h3>D</h3>
  <li><a href="#/"> daniel-smith/</a></li>
  <hr />
  <h3>G</h3>
  <li><a href="#/"> glen-smith/</a></li>
  <hr />
  <h3>J</h3>
  <li><a href="#/"> joe-smith/</a></li>
  <li><a href="#/"> johnny-smith/</a></li>
  <li><a href="#/"> joe-smith/</a></li>
</ul>

I did try to do this myself, but I simply wasn’t able to, I’m relatively new to JavaScript! Thanks.

Answer

Since putting h3 and hr inside a ul tag is not valid, I created this style with css. Just added a li node with splitter class.

The solution has 2 steps:

  1. Sort the list (using .sort() method)
  2. Create the titles.

Read the code and let me know if something not clear.

var list = $('ul'),
    items = $('li', list);

// sort the list
var sortedItems = items.get().sort(function(a, b) {
  var aText = $.trim($(a).text().toUpperCase()),
      bText = $.trim($(b).text().toUpperCase());
  
   return aText.localeCompare(bText);
});

list.append(sortedItems); 

// create the titles
var lastLetter = '';
list.find('li').each(function() {
  var $this = $(this),
      text = $.trim($this.text()),
      firstLetter = text[0];

  if (firstLetter != lastLetter) {
    $this.before('<li class="splitter">' + firstLetter);
    lastLetter = firstLetter;
  }
});
.splitter {
  border-top: 1px solid;
  font-size: 1.25em;
  list-style: none;
  padding-top: 10px;
  text-transform: uppercase;
  padding-bottom: 10px;
  margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#/"> john-smith/</a></li>
  <li><a href="#/"> joe-smith/</a></li>
  <li><a href="#/"> glen-smith/</a></li>
  <li><a href="#/"> daniel-smith/</a></li>
  <li><a href="#/"> johnny-smith/</a></li>
</ul>

Leave a Reply

Your email address will not be published. Required fields are marked *