Skip to content

Instantly share code, notes, and snippets.

@ChathuraGH
Created December 1, 2023 19:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChathuraGH/20b78cc09a648a1f428d31c2bec1ba77 to your computer and use it in GitHub Desktop.
Save ChathuraGH/20b78cc09a648a1f428d31c2bec1ba77 to your computer and use it in GitHub Desktop.
function countChrOccurence ('hello') {
let charMap = new Map();
const count = 0;
for (const key of str) {
charMap.set(key,count); // initialize every character with 0. this would make charMap to be 'h'=> 0, 'e' => 0, 'l' => 0,
}
for (const key of str) {
let count = charMap.get(key);
charMap.set(key, count + 1);
}
// 'h' => 1, 'e' => 1, 'l' => 2, 'o' => 1
for (const [key,value] of charMap) {
console.log(key,value);
}
// ['h',1],['e',1],['l',2],['o',1]
}
//source
// https://stackoverflow.com/questions/19480916/count-number-of-occurrences-for-each-char-in-a-string
// https://stackoverflow.com/a/62781405/13861187
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment