loading...
Cover image for JavaScript Katas: Count the number of each character in a string

JavaScript Katas: Count the number of each character in a string

miku86 profile image miku86 Updated on ・3 min read

JavaScript Katas with miku86 (21 Part Series)

1) JavaScript Katas: Split a number array into odd and even numbers 2) JavaScript Katas: Count the number of each character in a string 3 ... 19 3) JavaScript Katas: Remove all exclamation marks from the end 4) JavaScript Katas: Correct the mistakes of the character recognition software 5) JavaScript Katas: Calculate total amount of points 6) JavaScript Katas: Abbreviate a two word name 7) JavaScript Katas: Count sheep 8) JavaScript Katas: Card Suit 9) JavaScript Katas: Divisible By 10) JavaScript Katas: Remove duplicates 11) JavaScript Katas: Polish Alphabet 12) JavaScript Katas: Well of Ideas - Easy 13) JavaScript Katas: Whose Move 14) JavaScript Katas: Repeat it 15) JavaScript Katas: Count lowercase letters 16) JavaScript Katas: Sort and Star 17) JavaScript Katas: Is it a palindrome? 18) JavaScript Katas: Freudian Translator 19) JavaScript Katas: Position in Alphabet 20) JavaScript Katas: Every possible sum of two digits 21) JavaScript Katas: Missing values

Intro 🌐

I take interesting katas of all levels and explain how to solve them.

Problem solving is an important skill, for your career and your life in general.

You'd better learn to solve problems!


Source

I take the ideas for the katas from different sources and re-write them.

Today's source: Codewars


Understanding the Exercise ❗

First, we need to understand the exercise!

This is a crucial part of (software) engineering.

Go over the exercise explanation again until you understand it 100%.

Do NOT try to save time here.

My method to do this:

  1. Input: What do I put in?
  2. Output: What do I want to get out?

Today's exercise

Write a function countAmountOfEachCharacter, that accepts one parameter: inputString, a valid string.

The function should return an object. The object has a key for every character that exists at least once in the string.
The value for each key is how many times that character exists in the string.


Input: a string.

Output: an object with keys for the existing characters and values for how many times that character exists in the string.


Thinking about the Solution 💭

I think I understand the exercise (= what I put into the function and what I want to get out of it).

Now, I need the specific steps to get from input to output.

I try to do this in small baby steps.

  • loop over the input string
  • if the character never has been seen before, add it to the object with a count of 1
  • if the character has been seen before, increase its count by 1
  • return the object with every key-value pair

Example:

  • Input: "bee"
  • Round 1: { "b": 1 } // next character is "b", which has never been seen before, therefore add it to the object with a count of 1
  • Round 2: { "b": 1, "e": 1 } // next character is "e", which has never been seen before, therefore add it to the object with a count of 1
  • Round 3: { "b": 1, "e": 2 } // next character is "e", which HAS been seen before, therefore increase its count by 1
  • Output: { "b": 1, "e": 2 } // return the object with every key-value pair

Implementation (for loop) ⛑

function countAmountOfEachCharacter(inputString) {
  const returnObject = {};

  // loop over input string
  for (let i = 0; i < inputString.length; i++) {
    // check if character has been seen before
    if (returnObject.hasOwnProperty(inputString[i])) {
      // increase its count by 1
      returnObject[inputString[i]] += 1;
    } else {
      // add it to the object with a count of 1
      returnObject[inputString[i]] = 1;
    }
  }

  return returnObject;
}

Result

console.log(countAmountOfEachCharacter("bee"));
// { b: 1, e: 2 }

console.log(countAmountOfEachCharacter("mississippi"));
// { m: 1, i: 4, s: 4, p: 2 }

Warning

If you use emojis in your string, you should avoid the normal for-loop.

Thanks to Benito van der Zander for commenting!


Implementation (for of-loop) ⛑

function countAmountOfEachCharacter(inputString) {
  const returnObject = {};

  // loop over input string
  for (const character of inputString) {
    // check if character has been seen before
    if (returnObject.hasOwnProperty(character)) {
      // increase its count by 1
      returnObject[character] += 1;
    } else {
      // add it to the object with a count of 1
      returnObject[character] = 1;
    }
  }

  return returnObject;
}

Result

console.log(countAmountOfEachCharacter("bee"));
// { b: 1, e: 2 }

console.log(countAmountOfEachCharacter("mississippi"));
// { m: 1, i: 4, s: 4, p: 2 }

Implementation (Functional) ⛑

function countAmountOfEachCharacter(inputString) {
  // convert the string to an array
  return [...inputString].reduce(
    (accumulated, currentChar) =>
      // check if character has been seen before
      accumulated.hasOwnProperty(currentChar)
        ? { ...accumulated, [currentChar]: accumulated[currentChar] + 1 } // increase its count by 1
        : { ...accumulated, [currentChar]: 1 }, // add it to the object with a count of 1
    {} // start with an empty object
  );
}

Result

console.log(countAmountOfEachCharacter("bee"));
// { b: 1, e: 2 }

console.log(countAmountOfEachCharacter("mississippi"));
// { m: 1, i: 4, s: 4, p: 2 }

Playground ⚽

You can play around with the code here


Next Part ➡️

Great work, mate!

Next time, we'll solve the next kata. Stay tuned!

If I should solve a specific kata, shoot me a message here.

If you want to read my latest stuff, get in touch with me!


Further Reading 📖


Questions ❔

  • Do you like to solve katas?
  • Which implementation do you like more? Why?
  • Any alternative solution?

JavaScript Katas with miku86 (21 Part Series)

1) JavaScript Katas: Split a number array into odd and even numbers 2) JavaScript Katas: Count the number of each character in a string 3 ... 19 3) JavaScript Katas: Remove all exclamation marks from the end 4) JavaScript Katas: Correct the mistakes of the character recognition software 5) JavaScript Katas: Calculate total amount of points 6) JavaScript Katas: Abbreviate a two word name 7) JavaScript Katas: Count sheep 8) JavaScript Katas: Card Suit 9) JavaScript Katas: Divisible By 10) JavaScript Katas: Remove duplicates 11) JavaScript Katas: Polish Alphabet 12) JavaScript Katas: Well of Ideas - Easy 13) JavaScript Katas: Whose Move 14) JavaScript Katas: Repeat it 15) JavaScript Katas: Count lowercase letters 16) JavaScript Katas: Sort and Star 17) JavaScript Katas: Is it a palindrome? 18) JavaScript Katas: Freudian Translator 19) JavaScript Katas: Position in Alphabet 20) JavaScript Katas: Every possible sum of two digits 21) JavaScript Katas: Missing values

Posted on by:

miku86 profile

miku86

@miku86

Mentor & Educator & Senior Web Developer - I help people to reach their (career) goals. => https://miku86.com/mentoring

Discussion

markdown guide
 

Here is my reduce solution

const result = text.split("").reduce((acc,val)=>{
  acc[val]=(acc[val]||0)+1;
  return acc;
},{})
 

Shorter version:

const result = [...text].reduce(
  (acc,val)=>(acc[val]=~~acc[val]+1,acc), {}
)
 
 

Golfed. Can anyone go smaller? 😛

let c=t=>[...t].reduce((a,v)=>(a[v]=~~a[v]+1,a),{})
 

Hey Jon,

we can remove the let 😜

 

Careful, the first for-loop does not work with emojis

 

Hey Benito,

thanks for your answer!
Can you tell me which emojis you tested?

I added a test case to my playground and it seems to work.

Greetings
Michael

 

Alright!
I tried some different ones and found some, that result in a question mark.

So I researched the problem:

I just updated the post, thank you!