Skip to content

Instantly share code, notes, and snippets.

@msaxena25
Last active April 29, 2023 08:17
Show Gist options
  • Save msaxena25/62d17a1c9b1e507f2eafd83fc7d54db0 to your computer and use it in GitHub Desktop.
Save msaxena25/62d17a1c9b1e507f2eafd83fc7d54db0 to your computer and use it in GitHub Desktop.
JavaScript Count Duplicate Characters in a String Best way
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}
@soureshkhandelwal
Copy link

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