如何在单词数组中找到字谜?
How can I find anagrams in an array of words?
我正在尝试从一组单词中获取所有字谜:
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);
我正在尝试从一组单词中获取所有字谜:
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);