How to use Sorting In Javascript
- Sort the given string.
- Loop through the sorted string to find the duplicates.
- If the next character is the same as the current character then we keep on counting the occurrence of that char.
- If the count is greater than one then we print the character and its count.
Example: In this example we are using Sorting
function printDuplicates(str) {
let len = str.length;
// Sorting the string
str = str.split('').sort().join('');
// Loop through the sorted string to find duplicates
for (let i = 0; i < len; i++) {
let count = 1;
// Counting the occurrences of each character
while (i < len - 1 && str[i] == str[i + 1]) {
count++;
i++;
}
// Printing the duplicate character and its count
if (count > 1) {
console.log(str[i] + ", count = " + count);
}
}
}
let str = "w3wiki";
printDuplicates(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