How to use Object as a Frequency Counter In Javascript
In this approach, we use an object as a frequency counter to track the occurrence of each character in the string. We iterate through the string, incrementing the count of each character in the object. After iterating through the string, we check the object to identify which characters have a count greater than 1, indicating that they are repeated.
const str = "w3wiki";
const charCount = {};
// Count occurrences of each character
for (const char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
const duplicates = [];
// Find characters with count > 1
for (const char in charCount) {
if (charCount[char] > 1) {
duplicates.push(char);
}
}
// Print duplicates or no duplicates message
if (duplicates.length > 0) {
console.log(`The duplicate characters: ${duplicates.join(', ')}`);
} else {
console.log(`The string "${str}" has no duplicate characters.`);
}
Output
The duplicate characters: G, e, k, s
JavaScript Program to Check for Repeated Characters in a String
In this article, we are going to see various methods with which you can detect repeated characters in a string. Checking for repeated characters in a string involves examining the string’s content to identify if any character occurs more than once. This helps detect duplications or repetitions within the text.
Input: Str = “w3wiki”
Output:
e, count = 4
g, count = 2
k, count = 2
s, count = 2
Explanation: e,g,k,and s are characters which are occured in string in more than one times.
There are several methods that can be used to Check for repeated characters in a string JavaScript.
Table of Content
- Using sort() method with for…of loop
- Using a Set in JavaScript
- Without using Extra Data Structure
- Using a Map
- Using Object as a Frequency Counter:
We will explore all the above methods along with their basic implementation with the help of examples.
Contact Us