📖 Scenario: You work in a word game company. You need to group words that are anagrams of each other to help players find word matches quickly.
🎯 Goal: Build a program that groups a list of words into arrays of anagrams using a hash map (JavaScript object).
📋 What You'll Learn
Create an array called words with the exact words: 'eat', 'tea', 'tan', 'ate', 'nat', 'bat'
Create an empty object called anagramGroups to store grouped anagrams
Use a for loop with variable word to iterate over words
Inside the loop, create a variable sortedWord that holds the letters of word sorted alphabetically
Use sortedWord as a key in anagramGroups to group words
Print the values of anagramGroups as an array of arrays
💡 Why This Matters
🌍 Real World
Grouping anagrams helps in word games, search engines, and spell checkers to find related words quickly.
💼 Career
Understanding hash maps and string manipulation is essential for software developers working on text processing and data grouping tasks.
Progress0 / 4 steps
1
Create the list of words
Create an array called words with these exact strings: 'eat', 'tea', 'tan', 'ate', 'nat', 'bat'
DSA Javascript
Hint
Use square brackets [] to create an array and separate words with commas.
2
Create the hash map to hold groups
Create an empty object called anagramGroups to store grouped anagrams
DSA Javascript
Hint
Use curly braces {} to create an empty object.
3
Group words by sorted letters
Use a for loop with variable word to iterate over words. Inside the loop, create a variable sortedWord that holds the letters of word sorted alphabetically using word.split('').sort().join(''). Then, if sortedWord is not a key in anagramGroups, create it with an empty array. Finally, push word into anagramGroups[sortedWord].
DSA Javascript
Hint
Use word.split('') to split letters, .sort() to sort, and .join('') to join back.
Check if the key exists in the object before adding.
4
Print the grouped anagrams
Print the values of anagramGroups as an array of arrays using console.log(Object.values(anagramGroups))
DSA Javascript
Hint
Use Object.values(anagramGroups) to get all grouped arrays.
Practice
(1/5)
1. What is the main idea behind grouping anagrams using a hash map?
easy
A. Group words by their length using a hash map
B. Count the number of vowels in each word and group by count
C. Use the first letter of each word as the key in the hash map
D. Use sorted strings as keys to group words with the same letters
Solution
Step 1: Understand anagrams
Anagrams are words with the same letters in different orders, so sorting letters gives a unique key.
Step 2: Use sorted string as hash map key
By sorting each word and using it as a key, all anagrams map to the same key and can be grouped.
Final Answer:
Use sorted strings as keys to group words with the same letters -> Option D
Quick Check:
Sorted word keys group anagrams = C [OK]
Hint: Sort each word to find its anagram group key [OK]
Common Mistakes:
Grouping by word length only
Using first letter as key
Counting vowels instead of letters
2. Which of the following JavaScript code snippets correctly initializes an empty hash map to group anagrams?
easy
A. const map = {};
B. const map = Map();
C. const map = [];
D. const map = new Set();
Solution
Step 1: Identify hash map initialization in JavaScript
JavaScript objects ({}) are commonly used as hash maps for key-value pairs.
Step 2: Analyze the options
{} creates a simple hash map using bracket notation like map[key]. Map() without new throws TypeError. [] creates an array unsuitable for key-value pairs. new Set() stores unique values, not mappings.
Final Answer:
const map = {}; -> Option A
Quick Check:
Object literal {} is simplest hash map = A [OK]
Hint: Use {} to create a simple hash map in JavaScript [OK]
Common Mistakes:
Using array [] instead of object
Using Set which doesn't store key-value pairs
Confusing Map and object initialization
3. What is the output of the following code?
function groupAnagrams(words) {
const map = {};
for (const word of words) {
const sorted = word.split('').sort().join('');
if (!map[sorted]) map[sorted] = [];
map[sorted].push(word);
}
return Object.values(map);
}
console.log(groupAnagrams(['bat', 'tab', 'eat', 'tea', 'ate']));
medium
A. SyntaxError
B. [['bat'], ['tab'], ['eat'], ['tea'], ['ate']]
C. [['bat', 'tab'], ['eat', 'tea', 'ate']]
D. [['bat', 'tab', 'eat', 'tea', 'ate']]
Solution
Step 1: Sort each word and group in map
Words 'bat' and 'tab' both sort to 'abt', so grouped together. 'eat', 'tea', 'ate' all sort to 'aet', grouped together.
Step 2: Return grouped anagrams as array of arrays
[['bat', 'tab'], ['eat', 'tea', 'ate']] -> Option C
Quick Check:
Sorted keys group words = [['bat','tab'],['eat','tea','ate']] [OK]
Hint: Sort words, group by sorted key, return grouped arrays [OK]
Common Mistakes:
Returning flat list instead of grouped arrays
Not sorting words before grouping
Syntax errors from missing brackets
4. Find the error in this code snippet for grouping anagrams:
function groupAnagrams(words) {
const map = {};
for (const word of words) {
const sorted = word.sort().join('');
if (!map[sorted]) map[sorted] = [];
map[sorted].push(word);
}
return Object.values(map);
}
medium
A. map should be initialized as a Map object
B. word.sort() is invalid because word is a string, not an array
C. Missing return statement
D. Using Object.values on map is incorrect
Solution
Step 1: Identify the error in sorting
word is a string, and strings do not have a sort() method. It must be split into an array first.
Step 2: Correct approach to sort letters
Use word.split('').sort().join('') to sort letters of the string correctly.
Final Answer:
word.sort() is invalid because word is a string, not an array -> Option B
Quick Check:
Strings need split() before sort() = B [OK]
Hint: Split string to array before sorting letters [OK]
Common Mistakes:
Calling sort() directly on string
Not splitting string before sorting
Confusing Map object with plain object
5. Given the input array ['listen', 'silent', 'enlist', 'google', 'gogole', 'abc', 'cab'], which of the following is the correct grouped anagrams output using a hash map approach?
hard
A. [['listen', 'silent', 'enlist'], ['google', 'gogole'], ['abc', 'cab']]
B. [['listen', 'silent'], ['enlist', 'google'], ['gogole', 'abc', 'cab']]
C. [['listen'], ['silent'], ['enlist'], ['google'], ['gogole'], ['abc'], ['cab']]
D. [['listen', 'silent', 'enlist', 'google', 'gogole', 'abc', 'cab']]
Solution
Step 1: Sort each word to find keys
'listen', 'silent', 'enlist' all sort to 'eilnst'; 'google', 'gogole' sort to 'eggloo'; 'abc', 'cab' sort to 'abc'.
Step 2: Group words by sorted keys
Group words with same sorted key together: [['listen', 'silent', 'enlist'], ['google', 'gogole'], ['abc', 'cab']].
Final Answer:
[['listen', 'silent', 'enlist'], ['google', 'gogole'], ['abc', 'cab']] -> Option A
Quick Check:
Sorted keys group anagrams correctly = A [OK]
Hint: Sort letters, group by key, collect arrays [OK]
Common Mistakes:
Mixing groups with different sorted keys
Grouping by word length instead of letters
Returning flat list instead of grouped arrays
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.