Trying to add keys and values to a typescript object.
To do this I am sorting all the words and using the sorted word as the key in a map Object and adding values to the key which should be all the anagrams (as all anagrams sorted should match to the same key as they are the same sorted)
I don't know what I'm doing wrong with my JavaScript when adding items to the Object. It returns after my first attempt at adding a new key and value to the map object.
Any guidance on this would be greatly appreciate. I've tried it lots of different ways, even using the Map data structure itself, however map.Set() here overrides the last value stored when I actually want multiple values stored at a key.
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
function group(str: string[]) {
let map = {};
for (var word in str) {
let wordSorted = word
.split("")
.sort()
.join("");
map[wordSorted].push(word);
}
}
Right now I'm focusing on adding values to the JavaScript object that are the same sorted.
I will then try get the correct output.