Have you ever needed to count the occurrence of each character in a string? Perhaps you need to analyze user input, check for common patterns, or perform text processing. In any case, JavaScript provides an easy and efficient way to count characters using the charCount function.
Implementing the charCount function
The charCount function is a JavaScript function that takes a string as input and returns an object that represents the count of each character in the string. Let's take a closer look at how it works.
Let's see how the charCount function works with an example.
function charCount(str) {
let result = {};
for (let i = 0; i < str.length; i++) {
let char = str[i];
if (result[char] > 0) {
result[char]++;
} else {
result[char] = 1;
}
}
return result;
}
Explanation
The charCount function works by iterating over each character in the string using a loop. For each character, it checks whether it has already been seen by checking whether the character exists as a key in the result object. If the character is already in the result object, its count is incremented. Otherwise, a new key is added to the result object with a value of 1.
console.log(charCount("hello"));
// Output: {h: 1, e: 1, l: 2, o: 1}
- Analyzing User Input
- Data Analysis
- Text Processing