DEV Community

Rajesh Royal
Rajesh Royal

Posted on • Originally published at rajeshroyal.com on

Group Anagrams – LeetCode challenge Javascript solution Hashmap

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"]]
Enter fullscreen mode Exit fullscreen mode

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; 
};
Enter fullscreen mode Exit fullscreen mode

Submission Output on LeetCode:

code output on Leetcode Group Anagrams

Top comments (0)