javascript - 如何在单词数组中找到字谜?
问题描述
我正在尝试从一系列单词中获取所有字谜:
arr = ['cab','bac','tru']
预期的输出应该是:
{abc: ['cab','bac']}
我试图实现以下代码:
var words = ['cab', 'bac', 'mihir']
let result = {}
words.forEach(word => {
var a = word.split("").sort().join("");
result[word] = a
})
console.log(result)
如何迭代这些值,以便在它们具有相同值的情况下访问这些键?
解决方案
您可以将排序后的单词用作对象中的键,并收集与数组中的键匹配的每个单词:
var words = ['cab', 'bac', 'mihir']
let result = {}
for (const word of words) {
const sorted = word.split("").sort().join("");
if (sorted in result) {
// If there is already an entry in the result, append this word
result[sorted].push(word);
} else {
// Otherwise, create one
result[sorted] = [word];
}
}
console.log(result);
推荐阅读
- reactjs - 制作一个 React Material-UI 组件以粘在屏幕的右下角
- java - 让动画更流畅
- r - 合并来自多个 data.tables 的唯一行并添加属性详细信息
- windows - 如何使用 PowerShell 进行“干净启动”?
- c - 您如何制作一个随机数生成器,可以在数字 2 或 3 之间进行选择。(不是 1、2、3)
- java - 使用 Java REST API 从 Firebase 存储中上传的文件中获取公共下载 URL
- excel-formula - 如何对从文本数据中提取的数字使用公式
- php - 在下拉选择中显示文件夹和子文件夹
- c# - 我需要用用户输入的“ - ”替换字符串中的所有元音
- cmake - 如何在不使用 CMake 的情况下在 KDevelop 中构建 Ninja 项目?