Group Anagrams Problem statement:
https://leetcode.com/problems/
Given an array of strings, group anagrams together.
Example:
**Input:** ["eat", "tea", "tan", "ate", "nat", "bat"],
**Output:** [["ate","eat","tea"], ["nat","tan"], ["bat"]]
Note:
- All inputs will be in lowercase.
- The order of your output does not matter.
Group Anagrams ES6 solution
/\*\* \* @param {string[]}
strs \* @return {string[][]} \*/
var groupAnagrams = function(strs) {
function logMapElements(value, key, map) {
lastarray.push(value.split(','))
//push value of the current key "key" = "ate","tea"
}
let map = new Map();
let lastarray = Array();
strs.map(function(crntvalue){
let orig = crntvalue;
let sorted = crntvalue.split('').sort().join('');
//sort the orignal array word
if(map.has(sorted)){
let crnt = map.get(sorted);
//get current keypair value
map.set(sorted, crnt += ','+orig)
//add new value with current key pair
}else{
map.set(sorted, orig);
//create key and value
}
});
map.forEach(logMapElements);
//iterate through each map element
return lastarray;
};
Top comments (0)