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:
charCount
: This object will store each character of the string as a key and the number of times it appears as the value.duplicates
: This array will store characters that appear more than once in the string.- First Loop: We loop through the string to count how many times each character appears.
- 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.