How to use Set() In Javascript
This approach uses two Sets to track characters in a string, seen set to store characters encountered, and duplicates set to store duplicate characters. It iterates over the string, adding characters to seen if they are not already there, or to duplicates if they are.
Example: In this example we are using Set().
function findDuplicates(str) {
const seen = new Set();
const duplicates = new Set();
for (let char of str) {
if (seen.has(char)) {
duplicates.add(char);
} else {
seen.add(char);
}
}
duplicates.forEach(char => {
const count = str.split(char).length - 1;
console.log(`${char}, count= ${count}`);
});
}
const str = "w3wiki";
findDuplicates(str);
Output
e, count= 4 g, count= 2 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