Group Anagrams
Description
Given an array of strings strs
, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""] Output: [[""]]
Example 3:
Input: strs = ["a"] Output: [["a"]]
Constraints:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i]
consists of lowercase English letters.
Solution(javascript)
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
// does not work on all cases
// let anagrams = {};
// for (let i = 0; i < strs.length; i++){
// let sorted = strs[i].split("").sort().join("");
// if(anagrams[sorted]) {
// anagrams[sorted] += "," + [strs[i]]
// } else {
// anagrams[sorted] = strs[i]
// }
// }
// let res = [];
// for (key in anagrams) {
// let value = anagrams[key].split(",")
// res.push(value)
// }
// return res;
let obj = {};
for (let str of strs) {
let letters = str.split("").sort().join("");
obj[letters] ? obj[letters].push(str) : obj[letters] = [str];
}
return Object.values(obj);
};