stevemcilwaine
6/6/2019 - 10:47 AM

Sorting whilst ignoring articles ('the', 'a' etc)

Example of a sort that ignores the articles a, the and an. bands is an example array of strings, strip is the arrow function that strips the article from a passed string, sortedBands is a copy of the array that the strip function is applied to and #bands is a container for the results to be put into on the page.

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

const strip = band => band.replace(/^(a |the |an )/i, '').trim();
const sortedBands = bands.sort( (a, b) => strip(a) > strip(b) ? 1 : -1 );

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