COUNT DUPLICATE CHARACTERS IN A STRING

Question : Write a program to Count Duplicate characters in a String.

Example : “canada”

  • c - 1 times
  • a - 3 times
  • n - 1 times
  • d - 1 times

Method 1

function countLetters(str) {
let newStr = str.toLowerCase();
let count = {}
for (let letter of newStr) {
if (count[letter]) {
count[letter] += 1;
} else {
count[letter] = 1;
}
}
return count;
}
console.log(countLetters("canada"));
//Prints: {c:1, a:3, n:1, d:1}
console.log(countLetters("javascript"));
//Prints: {j:1, a:2, v:1, s:1, c:1, r:1, i:1, p:1, t:1}