Array Sorting Example 3

Final companion example to my post on sorting JavaScript arrays.

by Lance Leonard

HTML

<p>Here are some book titles:</p>

<div id="pOutput"></div>

CSS

#pOutput { 
  white-space : pre;
  margin-left: 1em;
}

JavaScript

function writeTitle( strTitle ) {
    var obj = document.getElementById( "pOutput" );
    obj.textContent += strTitle + "\n";
}

   function removeLeadingArticle( sInput ) {
     var sResult = sInput.toLocaleLowerCase();
     var aArticles = [ 'a', 'an', 'the' ];
     var aWords = sResult.split(/\s/);
     if ( aArticles.indexOf( aWords[0] ) > -1 ) {
        sResult = aWords.slice( 1 ).join( ' ' );
     }   
     return sResult;
  }

var astrTitles = [
    "A Study in Scarlet",
    "The Sign of the Four",
    "The Adventures of Sherlock Holmes",
    "The Memoirs of Sherlock Holmes",
    "The Hound of the Baskervilles",
    "The Return of Sherlock Holmes",
    "His Last Bow",
    "The Valley of Fear",
    "The Case-Book of Sherlock Holmes"
];

var iTotal = astrTitles.length; 
if ( iTotal > 0 ) {
   
    if ( astrTitles.length > 1 ) {
      
       astrTitles.sort( function( a, b ) {
          var SortTermA = removeLeadingArticle( a );
          var SortTermB = removeLeadingArticle( b );
          return SortTermA.localeCompare( SortTermB );
       } );
    }    

    for ( var iTitles = 0; iTitles < iTotal; iTitles++ ) {
      var str = astrTitles[ iTitles ];
      writeTitle( str );
   }
}