loading...

Group Anagrams – LeetCode challenge Javascript solution Hashmap

rajeshroyal profile image Rajesh Royal Originally published at rajeshroyal.com on ・1 min read

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; 
};

Submission Output on LeetCode:

code output on Leetcode Group Anagrams

Posted on by:

rajeshroyal profile

Rajesh Royal

@rajeshroyal

Designer, Front-end Developer, Traveller, Hooper. I design and code beautifully simple things, and I love what I do.

Discussion

pic
Editor guide