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}
@lukebergmann
Copy link

Hey there, feel free to totally disregard this if you want, I know you didn't ask for my opinion haha. I was just polishing up my JS practice and I came across your code. Line eight shows the value incrementing the entire key-value pair that works as it should until you have more than double a letter. In the word "canada" your output would be {c: 1, a: 4, n: 1, d: 1} and in the word "canaada" your output would be {c: 1, a: 8, n: 1, d: 1}. Instead of incrementing the entire object I would just add one. Like this:
if(obj[str[i]]){ obj[str[i]] += 1; }

@Stan-l-e-y
Copy link

Thanks for the code msaxena and thanks for the revision on it Luke! I have to write similar code for a lab at school and this is exactly what I need but I'm having trouble understanding the if statements. From what I believe to be correct, the first if statement returns true if the parameter str is a string, correct? The second if and else statement that lies within the loop is difficult for me to understand, would you mind explaining it to me? Thank you!

@lukebergmann
Copy link

lukebergmann commented Jun 23, 2021

@Stan-l-e-y There are two main things to consider for this example, Knowing how loops work, and knowing how to access and add values to objects. For this specific example, the 'if' is checking if a letter has been added as a key in the object named obj. If a letter is a key in the object, or the 'if' statement is true, and it finds a matching letter in the string, it adds a value of 1 to the total. If a letter is not yet a key in the object, the 'if' statement is false, triggering the 'else' statement. The 'else' statement creates the key-value pair in the object and the loop continues.

If the string was "Canada" it would look something like this:

  1. The loop is triggered
  2. 'c' hits the first 'if' statement which IS NOT true because it is not a key in the object yet
  3. 'c' hits the 'else' statement and is added. This is the state of the object now {c: 1}
  4. 'a' hits the first 'if' statement which IS NOT because it is not a key in the object yet
  5. 'a' hits the 'else' statement and is added. This is the state of the object now {c: 1, a: 1}
  6. 'n' hits the first 'if' statement which IS NOT true because it is not a key in the object yet
  7. 'n' hits the 'else' statement and is added. This is the state of the object now {c: 1, a: 1, n: 1}
  8. 'a' hits the first 'if' statement which IS true because it is a key in the object
  9. 1 gets added to the 'a' key in the object. This is the state of the object now {c: 1, a: 2, n: 1}
  10. 'd' hits the first 'if' statement which IS NOT true because it is not a key in the object yet
  11. 'd' hits the 'else' statement and is added. This is the state of the object now {c: 1, a: 2, n: 1, d: 1}
  12. 'a' hits the first 'if' statement which IS true because it is a key in the object
  13. 1 gets added to the 'a' key in the object. This is the state of the object now {c: 1, a: 3, n: 1, d: 1}
  14. The loop runs out of letters in the string and the object is returned.
  15. {c: 1, a: 3, n: 1, d: 1}

Hope this helps with this example, let me know if you have any other questions!
Luke

@Stan-l-e-y
Copy link

@lukebergmann Thank you so much for the response, I really appreciate it! I just have one more question if you don't mind. How would I go about trying to remove the occurrences of letters with only 1 value, in essence only including repeated characters in the output. I was thinking of somehow targeting the certain letters with a value of 1 and removing them in some way possibly via a method. I just haven't learned objects yet and I don't know how to target those certain values and remove them.

Thanks again!
Stanley

@lukebergmann
Copy link

lukebergmann commented Jun 25, 2021

@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!

  1. Object.keys() - Returns an array.
  2. Array.prototype.filter() - Creates a new array with all elements that pass the test implemented by the provided function.
  3. Array.prototype.includes() - Determines whether an array includes a certain value among its entries.
  4. Array.prototype.reduce() - Can help build the new Object with only the specific key-values you want inside.

Referenced from this StackOverflow Article

Have fun!
Luke

@Stan-l-e-y
Copy link

@lukebergmann Thanks once again Luke! I'll take a look at these and explore my possibilities. Cheers!

@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