JavaScript 30 – Day 17: Sorting Without Leading Articles

Welcome to my recap of Day 17 of the free JavaScript 30 online video course by Wes Bos. In case you really have not yet heard of the course, quickly head over to it and get started right away! 🙂

Please refer to the JavaScript 30 archive for all recap posts.

Objective

On Day 17, the task is to sort a given array of band names (i.e., strings) but ignore potential leading articles such as “a”, “an” and “the”, and then insert the band names as individual items into an empty unordered list.

The provided starter files include an HTML file that contains the bands array as well as some inline CSS that takes care of the styling. As usual, for my fork of the JavaScript 30 repository, I moved the CSS into a separate file.

I stopped the video right after the objective has been made clear, and started implementing it on my own.

Conception

Yeah, well, the conception is … short:

  • sort an array of strings alphabetically;
  • ignore any leading articles;
  • insert into an HTML list.

Implementation

Following the conception, we first have to sort the band names:

function stripLeadingArticle( string ) {
    return string.replace( /^(an?|the)\s/i, '' );
}

const sortedBands = bands.sort( ( a, b ) => stripLeadingArticle( a ) > stripLeadingArticle( b ) );

Now, we only have to turn each band name into a list item, and insert these into the list.

document.getElementById( 'bands' ).innerHTML = sortedBands.map( ( b ) => `<li>${b}</li>` ).join('');

Done. 🙂

Refinement

Wow, the two solutions (Wes’s and mine) are round about 98% the same.

One of the differences is that my regular expression is not as verbose—/^(an?|the)\s/i vs. /^(a |an |the )/i—and I didn’t use trim(), what you don’t have to when using \s+ instead of \s.

Like mentioned in previous posts, when querying a DOM element by ID, I tend to use getElementById() instead of using the multi-purpose querySelector(). But that is just a habit of mine, as the speed difference is negligible.

Last but not least, I don’t see any advantage in explicitly returning 1 and -1 in a sort callback; I simply perform a comparison, which results in true or false.

Live Demo

Want to see this in action? Well, here is a live demo. 🙂

Retrospection

Nothing new, which isn’t a bad thing. 🙂

And You?

JavaScript 30 is free! So, unless you already did this on your own, what’s your reason not to? 🙂

Leave a Reply

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