📖 Scenario: You are working in a small bookstore. You want to count how many times each book title appears in a list of sold books to understand which books are popular.
🎯 Goal: Build a frequency counter using a hash map (JavaScript object) to count how many times each book title appears in the sales list.
📋 What You'll Learn
Create an array called soldBooks with exact book titles given
Create an empty object called bookFrequency to store counts
Use a for loop with variable book to iterate over soldBooks
Inside the loop, update bookFrequency to count each book's occurrences
Print the bookFrequency object at the end
💡 Why This Matters
🌍 Real World
Counting how many times items appear in a list is useful in sales, surveys, and data analysis.
💼 Career
Frequency counters are common in programming jobs for data processing, analytics, and building recommendation systems.
Progress0 / 4 steps
1
Create the sales data array
Create an array called soldBooks with these exact book titles in order: 'The Hobbit', '1984', 'The Hobbit', 'The Catcher in the Rye', '1984', 'The Hobbit'.
DSA Javascript
Hint
Use square brackets [] to create an array and include the exact book titles as strings separated by commas.
2
Create the frequency counter object
Create an empty object called bookFrequency to store the count of each book.
DSA Javascript
Hint
Use curly braces {} to create an empty object and assign it to bookFrequency.
3
Count the frequency of each book
Use a for loop with variable book to iterate over soldBooks. Inside the loop, update bookFrequency[book] to count how many times each book appears. If the book is not yet in bookFrequency, set its count to 1; otherwise, add 1 to its existing count.
DSA Javascript
Hint
Use for (const book of soldBooks) to loop. Check if bookFrequency[book] exists. If yes, add 1; if no, set to 1.
4
Print the frequency counter
Print the bookFrequency object using console.log(bookFrequency) to see the count of each book.
DSA Javascript
Hint
Use console.log(bookFrequency) to print the object showing counts.
Practice
(1/5)
1. What is the main purpose of using a frequency counter pattern with a hash map in JavaScript?
easy
A. To reverse the order of elements in an array
B. To sort the elements in ascending order
C. To remove duplicate items from a list
D. To count how many times each item appears in a collection
Solution
Step 1: Understand frequency counter pattern
The frequency counter pattern uses a hash map to store counts of each item in a collection.
Step 2: Identify the purpose
Counting occurrences helps to quickly check how many times each item appears.
Final Answer:
To count how many times each item appears in a collection -> Option D
Quick Check:
Frequency counter = count items [OK]
Hint: Frequency counter counts items using a hash map [OK]
Common Mistakes:
Confusing frequency counting with sorting
Thinking it removes duplicates instead of counting
Assuming it reverses arrays
2. Which of the following is the correct way to initialize an empty frequency counter object in JavaScript?
easy
A. const freq = [];
B. const freq = {};
C. const freq = null;
D. const freq = 0;
Solution
Step 1: Identify correct data structure for frequency counter
A frequency counter uses an object (hash map) to store keys and counts.
Step 2: Choose correct initialization syntax
In JavaScript, an empty object is created with curly braces {}.
Final Answer:
const freq = {}; -> Option B
Quick Check:
Empty object = {} [OK]
Hint: Use {} to create empty object for frequency counter [OK]
Each character's count is incremented in freq object: 'a' appears 3 times, 'b' 2 times, 'c' 1 time.
Step 2: Construct final frequency object
freq = {"a": 3, "b": 2, "c": 1} after loop ends.
Final Answer:
{"a": 3, "b": 2, "c": 1} -> Option A
Quick Check:
Count 'a' = 3, 'b' = 2, 'c' = 1 [OK]
Hint: Count each char incrementally using freq[char] = (freq[char]||0)+1 [OK]
Common Mistakes:
Mixing counts of 'a' and 'b'
Not initializing counts properly
Using arrays instead of objects for counting
4. Identify the error in the following frequency counter code and select the fix:
const arr = ['x', 'y', 'x', 'z'];
const freq = {};
for (let i = 0; i < arr.length; i++) {
freq[arr[i]] += 1;
}
console.log(freq);
medium
A. Initialize freq[arr[i]] to 0 before adding 1
B. Change for loop to for...of loop
C. Use freq.push(arr[i]) instead of freq[arr[i]]
D. Declare freq as an array instead of object
Solution
Step 1: Understand the error cause
freq[arr[i]] is undefined initially, so adding 1 causes NaN.
Step 2: Fix by initializing count
Set freq[arr[i]] = 0 if undefined before adding 1.
Final Answer:
Initialize freq[arr[i]] to 0 before adding 1 -> Option A
Quick Check:
Initialize before increment to avoid NaN [OK]
Hint: Always initialize count to 0 before incrementing [OK]
Common Mistakes:
Trying to push to object as if array
Ignoring undefined initial values
Changing loop type unnecessarily
5. Given two arrays, arr1 = [1, 2, 2, 3] and arr2 = [2, 3, 3, 4], which code snippet correctly checks if arr2 contains the same frequency of elements as arr1 using the frequency counter pattern?
hard
A. const freq1 = {};
const freq2 = {};
for (const num of arr1) freq1[num] = (freq1[num] || 0) + 1;
for (const num of arr2) freq2[num] = (freq2[num] || 0) + 1;
for (const key in freq1) {
if (freq1[key] !== freq2[key]) return false;
}
return true;
B. const freq = {};
for (const num of arr1) freq[num] = 1;
for (const num of arr2) freq[num] = 0;
return Object.values(freq).every(v => v === 0);
C. const freq = {};
for (const num of arr1) freq[num] = (freq[num] || 0) + 1;
for (const num of arr2) freq[num] -= 1;
for (const key in freq) {
if (freq[key] !== 0) return false;
}
return true;
We must count frequencies in both arrays and compare counts for each element.
Step 2: Analyze each code snippet
const freq = {};
for (const num of arr1) freq[num] = (freq[num] || 0) + 1;
for (const num of arr2) freq[num] -= 1;
for (const key in freq) {
if (freq[key] !== 0) return false;
}
return true;
This uses a single object: increments for arr1, decrements for arr2 (NaN for extras), checks all zero. Handles extras (NaN≠0), shortages (positive≠0), overcounts (negative≠0).
Final Answer:
const freq = {}; increment arr1, decrement arr2, check all zero -> Option C
Quick Check:
Single freq: +arr1, -arr2, all zero? [OK]
Hint: Increment arr1 counts, decrement arr2, check all zero for same frequency [OK]
Common Mistakes:
Not comparing all keys in both frequency counters
Overwriting counts instead of incrementing
Using single frequency object incorrectly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.