Sort without articles

This is the 17th project of WesBos's JS30 series. To see the whole 30 part series, click here Today we learn how to sort HTML elements based based on their text content.

The video can be found here

The codepen for the starter code

The data we have at hand

const bands = ['The Plot in You', 'The Devil Wears Prada', 'Pierce the Veil', 'Norma Jean', 'The Bled', 'Say Anything', 'The Midway State', 'We Came as Romans', 'Counterparts', 'Oh, Sleeper', 'A Skylit Drive', 'Anywhere But Here', 'An Old Dog'];

We need to insert the sorted data as <li> elements into

<ul id="bands"></ul>

While sorting the data we need to ignore articles such as the, an, a.

Steps to take

  • Call standard sort on the array
  • Function to strip the strings
  • Compare the stripped version
  • Add the elements to the ul#bands

Call standard sort on the array

First we sort normally, with the articles

const sortedBands = bands.sort((a, b) => a > b ? 1 : -1);

//["A Skylit Drive", "An Old Dog", "Anywhere But Here", "Counterparts", "Norma Jean", "Oh, Sleeper", "Pierce the Veil", "Say Anything", "The Bled", "The Devil Wears Prada", "The Midway State", "The Plot in You", "We Came as Romans"]

Function to strip the strings

We'll use a RegEx to find any instance of articles (/i implies case insensitivity), and reduce them to nothing.

function strip(bandName) {
  return bandName.replace(/^(a |the |an )/i, '').trim();
}

Compare the stripped version

const sortedBands = bands.sort((a, b) => strip(a) > strip(b) ? 1 : -1);

Add the elements to the list

Map the list data to a list of strings of "<li>"'s. Then concatenate them and set them to the inner html of the <ul>

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

Finished codepen