All Articles

Sort Bands without Articles

This is day 17 in my #javascript30 journey. This is the free course from Wes Bos that lets you brush up on your JavaScript skills via 30 projects.

Yesterday we worked on a CSS Text Shadow Mouse Move Effect. You can keep track of all the projects we’re building here.

Today we’re exploring Sorting Band Names without Articles.


Day 17 - Sorting Band Names without Articles

Today we are working with Array.sort to sort this list of band names (minus the articles like a or an or the):

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',
]

First up we need to have a function that strips the articles from the front of the band name. We don’t want to alter the data but we want to be able to call this function when we are sorting our data.

We can use regex to replace any instances of a, an or the with nothing. We also need to add an i so we are indiscriminate of the case.

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

Next, we want to sort the bands. We will use the Array.sort method and within the arrow function we call the strip function:

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

Note: This is a refactored version of my earlier function:

const sortedBands = bands.sort(function (a, b){  
  if(strip(a) > strip(b) {
    return 1
  } else {
    return -1
  }
})

Both of these functions work but the refactored one makes use of the clean arrow function and its implicit return.


Now that the array has been sorted we can insert the bands into the HTML document:

document.querySelector('#bands').innerHTML =  
  sortedBands
    .map(band => `

${band} `) .join(”)

This looks like:

Sorted bands - ignoring articles


As there is no interactivity available in todays project I have opted not to publish it.

You can keep track of all the projects in this JavaScript30 challenge here.