I want to Check if the characters of a string have equal duplicate
if I enter :"abaababb" returns true because I have 4 'a' and 4 'b' in that string
if I enter : "addda" returns false because I have 2 'a' and 3 'd'
I tryed to check the duplicates but I found out I have to do it for some characters
CodePudding user response:
just need to create an empty object and loop through each character and increment the value associated with the key. Keep track of the highest value so we can easily use every on the array from Object.values and check if all character counts match this value
let check = "abaababb";
let check2 = "addda";
function hasEqualCharacters( input ) {
let characters = {};
let highestCount = 0;
for( let i =0; i < input.length; i ) {
if( characters[input[i]]) {
characters[input[i]] ;
if( highestCount < characters[input[i]]) {
highestCount = characters[input[i]];
}
} else {
characters[input[i]] = 1;
}
}
return Object.values(characters).every( (charCount) => {
return charCount === highestCount;
});
}
console.log(hasEqualCharacters(check));
console.log(hasEqualCharacters(check2));
Can see it working here https://playcode.io/1024243