可以使用 JavaScript 的 reduce() 方法和下标运算符来实现。
例如,假设有如下字符串数组:
const strings = ['apple', 'banana', 'avocado', 'cherry', 'date', 'grape'];
可以按照第一个字母将它们分组,代码如下:
const groupedStrings = strings.reduce((acc, str) => { const firstLetter = str[0]; if (!acc[firstLetter]) { acc[firstLetter] = []; } acc[firstLetter].push(str); return acc; }, {});
最终结果为:
{ "a": ["apple", "avocado"], "b": ["banana"], "c": ["cherry"], "d": ["date"], "g": ["grape"] }
这样,我们就成功将字符串数组按照第一个字母分组了。