JS首字母進行分類合並加排序


let array = ['fds', 'ewfg1', 'cvd', 'ew', 'qer', 'jjh', 'rth', 'asd', 'vsd', 'tteh', 'fxv'];
let map = {};
for(let i = 0; i < 26; i++){
    const key = String.fromCharCode(65 + i) //A-Z賦給key當作鍵
    map[key] = {
        title: key,
        items: []
    }
    array.map((v,k)=>{      //遍歷數組
        let firstIndex = v.charAt(0).toUpperCase();//首字母
        if(firstIndex.toUpperCase() == String.fromCharCode(65+i)){//統一轉成大寫進行逐個判斷
            map[key].items.push(v)//push進相對應的數組里頭
        }
    })
    // //如果當前的數組里頭為空,則跳過。
    if(map[key].items === undefined || map[key].items.length == 0){
        continue;
    }else{
        this.newArr.push(map[key])//將分類好的每個對象 合並在一個數組里面
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM