Skip to content

Group Anagrams – LeetCode challenge Javascript solution Hashmap

Written on 9th Apr 2020

Group Anagrams Problem statement:

Given an array of strings, group anagrams together.


["eat", "tea", "tan", "ate", "nat", "bat"]
, Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]


  • 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) {
           //push value of the current key "key" = "ate","tea"
        let map = new Map();
        let lastarray = Array();{
            let orig = crntvalue;
            let sorted = crntvalue.split('').sort().join('');
             //sort the orignal array word
                let crnt = map.get(sorted); //get current keypair value
                map.set(sorted,  crnt += ','+orig) 
                 //add new value with current key pair
                map.set(sorted, orig); //create key and value
        map.forEach(logMapElements); //iterate through each map element
        return lastarray;

Submission Output on LeetCode:

Rajesh-Royal on leetcode