假设我们有一个这样的名称数组-
const arr = ["Simon", "Mike", "Jake", "Lara", "Susi", "Blake", "James"];
我们需要编写一个包含一个这样的数组的JavaScript函数。该函数应返回具有两个属性的对象数组-
字母->名称分组的字母
名称->属于该组的名称数组
为此的代码将是-
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' ] } ]