I am trying to get all anagrams from a array of words:
arr = ['cab','bac','tru']
The expected output is supposed to be:
{abc: ['cab','bac']}
I tried to implement the below code:
var words = ['cab', 'bac', 'mihir']
let result = {}
words.forEach(word => {
var a = word.split("").sort().join("");
result[word] = a
})
console.log(result)
How do I iterate over the values so that I can access the keys if they have the same values?
CodePudding user response:
You can use the sorted words as keys in an object, and collect each word that matches the key in an array:
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);