JavaScript 30 – Day 17: Sorting Without Leading Articles

Written by Thorsten Frommen

Thorsten is a certified PHP engineer, web development professional and tester. He has been working on the web since 2000, and with (and on) WordPress since 2005. Thorsten is a Senior WordPress Engineer at Human Made.

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.

Refinement

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.