Group Anagrams – LeetCode challenge Javascript solution Hashmap

author-avatarRAJESH, April 9, 2020

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

< PrevPost NextPost >

Start a project

Interested in working together? We should
queue up a chat. I’ll buy the coffee.

Living, learning, & leveling up
one day at a time.

Handcrafted by me © RJ21 Nagour alaa😅

Made with ♥ by

Copyright © Rajesh Royal 2021.