根據 JavaScript 中的第一個字母對姓名進行分組


假設我們有一個這樣的姓名陣列 −

const arr = ["Simon", "Mike", "Jake", "Lara", "Susi", "Blake", "James"];

我們需要編寫一個 JavaScript 函式來接收這樣一個數組。該函式應返回一個具有兩個屬性的物件陣列 −

  • letter -> 分組姓名的字母

  • names -> 屬於該組的一個姓名陣列

示例

程式碼如下 −

const arr = ["Simon", "Mike", "Jake", "Lara", "Susi", "Blake", "James"];
const groupNames = arr => {
   const map = arr.reduce((acc, val) => {
      let char = val.charAt(0).toUpperCase();
      acc[char] = [].concat((acc[char] || []), val);
      return acc;
   }, {});
   const res = Object.keys(map).map(el => ({
      letter: el,
      names: map[el]
   }));
   return res;
};
console.log(groupNames(arr));

輸出

控制檯中的輸出 −

[
   { letter: 'S', names: [ 'Simon', 'Susi' ] },
   { letter: 'M', names: [ 'Mike' ] },
   { letter: 'J', names: [ 'Jake', 'James' ] },
   { letter: 'L', names: [ 'Lara' ] },
   { letter: 'B', names: [ 'Blake' ] }
]

更新於: 10-10-2020

1 千+ 次瀏覽

開啟你的職業

完成課程獲得認證

立即開始
廣告