JS30 Day 17 筆記


Posted by GL on 2023-05-23

功能

將陣列去除某些特定文字後,再進行排序

Demo

step 1 : 用 regex 篩選文字

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

// 用 replace 與正則表達式將句子開頭的 a / the / an 去除
function strip(bandName){
  return bandName.replace(/^(a |the |an )/i,'').trim()
}

step 2 : 對 bands 進行篩選並且排序

//使用 sort 方法,會改變原有的陣列 => mutable

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

// ES6 箭頭函數與三元運算子簡化寫法
const sortedBands = bands.sort((a,b)=> strip(a) > strip(b)? 1:-1)

// 若要不改變原來的陣列,使用 [...array]  => immutable array
// const sortedBands =[...bands].sort((a,b)=> strip(a) > strip(b)? 1:-1)

step 3 : 將結果渲染到 HTML 中

//原先兩兩 <li></li> 的分隔符號是逗號(,),使用 join('')將中間的連接符號從逗號變成空白。
document.querySelector('#bands').innerHTML = 
  sortedBands
    .map(band => `<li>${band}</li>`)
    .join('')

參考資料:


#JS 30







Related Posts

DAY29:Array.diff

DAY29:Array.diff

AI輔導室|快速完成網格繪製

AI輔導室|快速完成網格繪製

Git筆記 - 建立及讀取github repo

Git筆記 - 建立及讀取github repo


Comments