iT邦幫忙

第 12 屆 iThome 鐵人賽

0
自我挑戰組

前端新手的學習筆記系列 第 32

Day32 - JS30 - 17 - Sort Without Articles

參考資料
Alex老師教學
pjchender筆記
JS30-Day17-Sort Without Articles


文字排序。
遇到開頭是the , a , an 就忽略,改用後方內容排序。


題目預設

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',
];
bands.sort();//陣列排序

抓取節點

const text = document.getElementById('bands');//ul

先看一下畫面和呈現的資料

text.innerHTML = bands.join('');

https://ithelp.ithome.com.tw/upload/images/20201019/2012153441nJnFnOin.png
加上<li>放入<ul>

text.innerHTML = bands
    .map(item => {
        return `<li>${item}</li>`;
    })
    .join('');

加上正則

// 正則
let filterItem = item => {
    // 開頭是a ,the ,an,都替換成空字串
    return item.replace(/^(a |the |an )/i, '').trim();
    // trim()刪除字串前後的空白
};
//陣列排序
bands.sort((a, b) => {
    return filterItem(a) > filterItem(b) ? 1 : -1;
});
// sort()是操作原陣列
// 使用新陣列的寫法
let sortBands = [...bands].sort((a, b) => {
    return filterItem(a) > filterItem(b) ? 1 : -1;
});
console.log(bands === sortBands); //false

連結


上一篇
Day31 - JS30 - 16 - Mouse Move Shadow
系列文
前端新手的學習筆記32
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言