How to use Hashing In Javascript
- Declare a unordered map of the char-int pair.
- Traverse the string using a loop and increase the count of the present char in the map.
- Iterate through the map and print a character that has a value greater than one in map.
Example: In this example we are using Hashing.
// JavaScript program to count all duplicates
// from string using maps
function printDups(str) {
let count = new Map();
for (let i = 0; i < str.length; i++) {
if (count.has(str[i])) {
count.set(
str[i],
count.get(str[i]) + 1
);
} else {
count.set(str[i], 1);
}
//increase the count of characters by 1
}
//iterating through the unordered map
for (let [it, it2] of count) {
if (it2 > 1)
//if the count of characters is
//greater than 1 then duplicate found
console.log(it, ", count = ", it2);
}
}
/* Driver code*/
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