Exercise 10: Count Occurrences of Each Character

Problem Statement

Create a function `charCount(str)` that returns count of each character in string. Example: charCount("hello") → {h: 1, e: 1, l: 2, o: 1}

Sample Output:

charCount("hello") => {h: 1, e: 1, l: 2, o: 1}
charCount("aabbcc") => {a: 2, b: 2, c: 2}

Solution

const charCount = (str) => {
  const count = {};
  for (const char of String(str ?? "")) {
    count[char] = (count[char] || 0) + 1;
  }
  return count;
};

Explanation

Overall Goal:

  • String me har character ki frequency count karna.

Line 1: Function header

  • const charCount = (str) => {

Line 2: Count object

  • const count = {};

Line 3: Iterate characters

  • for (const char of String(str ?? ""))

Line 4: Increment count

  • count[char] = (count[char] || 0) + 1;

Real world:

  • Text analysis: character frequency.
  • Compression: frequency analysis.