simple JavaScript function to find duplicate characters in a string

function findDuplicateCharacters(str) {
    let charCount = {};
    let duplicates = [];

    // Loop through the string and count the occurrences of each character
    for (let char of str) {
        charCount[char] = (charCount[char] || 0) + 1;
    }

    // Find characters that appear more than once
    for (let char in charCount) {
        if (charCount[char] > 1) {
            duplicates.push(char);
        }
    }

    return duplicates;
}

// Example usage:
let result = findDuplicateCharacters("programming");
console.log(result); // Output: [ 'r', 'g', 'm' ]

Explanation:

  1. charCount: This object will store each character of the string as a key and the number of times it appears as the value.
  2. duplicates: This array will store characters that appear more than once in the string.
  3. First Loop: We loop through the string to count how many times each character appears.
  4. Second Loop: We check for characters that appear more than once and add them to the duplicates array.

This function will return an array of duplicate characters found in the input string.

Share.

Terry White is a professional technical writer, WordPress developer, Web Designer, Software Engineer, and Blogger. He strives for pixel-perfect design, clean robust code, and a user-friendly interface. If you have a project in mind and like his work, feel free to contact him

Leave A Reply