How to use For Loop In Javascript
In this approach, an object named charCount
to effectively maintain the frequency of characters in the string. It sequentially processes each character in the input string, increasing its count in the charCount
object. Once the character frequencies are established, the code then traverses through the charCount
object. It selectively prints characters that have occurrences greater than one, thereby accurately showcasing the duplicate characters along with the corresponding count of duplications.
Example: In this example, we are using a for loop.
function printDups(str) {
let charCount = {};
for (let i = 0; i < str.length; i++) {
let character = str[i];
charCount[character] =
(charCount[character] || 0) + 1;
}
for (let char in charCount) {
if (charCount[char] > 1) {
console.log(
char +
", count = " +
charCount[char]
);
}
}
}
let str = "w3wiki";
printDups(str);
Output
g, count = 2 e, count = 4 k, count = 2 s, count = 2
JavaScript Program to Print All Duplicate Characters in a String
In this article, we will learn how to print all duplicate characters in a string in JavaScript. Given a string S, the task is to print all the duplicate characters with their occurrences in the given string.
Example:
Input: S = “w3wiki”
Output:
e, count = 4
g, count = 2
k, count = 2
s, count = 2
Table of Content
- Using For Loop in JavaScript
- Using Sorting in JavaScript
- Using Hashing in JavaScript
- Using Set()
- Using Reduce Method in JavaScript