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} |
@lukebergmann Thanks once again Luke! I'll take a look at these and explore my possibilities. Cheers!
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
@Stan-l-e-y Not a worry! You are definitely on the right track with the method idea. Understanding objects can be a bit tricky if you have not really learnt them yet. If this was an array you could totally use the filter() method that would allow you to filter out the values that are not needed in the returned result. Unfortunately, this is not an array and does require a few extra steps. I won't go too far into it now, but once you start learning objects feel free to shoot me a message! MDN docs and StackOverflow are a great way to learn. For now, I'll leave a couple of hints here and you can give it a try yourself!
Referenced from this StackOverflow Article
Have fun!
Luke