首页 > 解决方案 > 如何在单词数组中找到字谜?

问题描述

我正在尝试从一系列单词中获取所有字谜:

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)

如何迭代这些值,以便在它们具有相同值的情况下访问这些键?

标签: javascriptarraysobjectkey-value

解决方案


您可以将排序后的单词用作对象中的键,并收集与数组中的键匹配的每个单词:

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);

推荐阅读