Javascript30-dustin

Sort Without Articles

摘要

今日要透過編排文章排序來複習sort, map, joinreplace, trim的使用。

內容

首先先把文章編排。

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

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

影片內多了一個排序說明:排序時不要參考a, an 及the

function strip(bandName){
  return bandName.replace(/^(a |an |the)/i, '').trim();
}
...strip(a)> strip(b)? 1 : -1;

今日課程就到這邊結束囉!以下是完整程式碼

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

function strip(bandName) {
  return bandName.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('');

</script>