How to find the duplicate characters in a string in Javascript

We can find duplicate characters in a string by using a for loop and a JavaScript object (dictionary) to store character counts.

Steps:

After the loop, print only those characters whose count is greater than 1 — these are the duplicates.

  • Get the string input.
  • Initialize an empty object to store character counts.
  • Loop through each character in the string.
  • For each character:
  • If it already exists in the object, increment its count by 1.
  • Otherwise, set its count to 1.

Example Code:

const str = “programming”;
const charCount = {};

let len = str.length;

for (let i = 0; i < len; i++) {
const char = str[i];

if (charCount[char]) {
charCount[char] += 1;
} else {
charCount[char] = 1;
}
}

// Display duplicate characters
console.log(“Duplicate characters:”);
for (let char in charCount) {
if (charCount[char] > 1) {
console.log(${char} - ${charCount[char]} times);
}
}

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x