Last active
April 29, 2023 08:17
-
-
Save msaxena25/62d17a1c9b1e507f2eafd83fc7d54db0 to your computer and use it in GitHub Desktop.
JavaScript Count Duplicate Characters in a String Best way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function duplicateCharCount(str) { | |
if(str) { | |
var obj = {}; | |
for(let i = 0; i < str.length; i++) { | |
if(obj[str[i]]){ | |
obj[str[i]] += obj[str[i]]; | |
}else { | |
obj[str[i]] = 1; | |
} | |
} | |
console.log(obj); | |
} | |
} | |
Run this Code > | |
duplicateCharCount("aabcdd"); | |
Output > | |
{a: 2, b: 1, c: 1, d: 2} |
let str= 'CormSquare';
let obj= {}
for(val of str){
obj[val] = (obj[val] || 0) + 1
}
console.log(obj)
Output: { C: 1, o: 1, r: 2, m: 1, S: 1, q: 1, u: 1, a: 1, e: 1 }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@lukebergmann Thanks once again Luke! I'll take a look at these and explore my possibilities. Cheers!