JavaScript如何按首字母为键将对应单词分组存入Map对象
问题根源
你的代码逻辑存在两个核心问题:
- 调用
myMap.set()存储单词时,若首字母对应的键已存在,新值会直接覆盖旧值,因此同首字母的单词只会保留最后遍历到的那一个,无法收集全部单词 - 没有做重复单词校验,若字符串中出现重复单词,会被重复存入对应位置,不符合「存储不重复单词」的要求
修改后代码
将每个键对应的值改为数组类型存储,遍历单词时先判断键是否存在、单词是否已在对应数组中,再执行添加操作:
function sortToMap(str){ let lowerString = str.toLowerCase(); let wordList = lowerString.split(" "); let myMap = new Map(); for(let i = 0; i < wordList.length; i++){ const currentWord = wordList[i]; const firstChar = currentWord[0]; // 首字母不存在时,初始化对应存储数组 if (!myMap.has(firstChar)) { myMap.set(firstChar, []); } const storedWords = myMap.get(firstChar); // 单词未重复时才存入数组 if (!storedWords.includes(currentWord)) { storedWords.push(currentWord); } } return myMap; } let myString = "Test string to check How it Works and hopefully it is fine"; console.log(sortToMap(myString));
运行输出
执行代码后得到的结果如下,完全符合需求逻辑:
Map(8) { 't' => [ 'test', 'to' ], 's' => [ 'string' ], 'c' => [ 'check' ], 'h' => [ 'how', 'hopefully' ], 'i' => [ 'it', 'is' ], 'w' => [ 'works' ], 'a' => [ 'and' ], 'f' => [ 'fine' ] }
注:你给出的预期结果中遗漏了h开头的
how单词,上述代码会按输入字符串的实际内容,完整收集所有首字母匹配的不重复单词。
内容的提问来源于stack exchange,提问作者Ruslan Anderson
相关产品推荐
相关产品推荐

