JavaScript Katas: Count the number of each character in a string
Tags: javascript, beginners, webdev, codenewbie
Published: 2020-07-10 10:23:46

---
title: "JavaScript Katas: Count the number of each character in a string"
description: "JavaScript Katas: Count the number of each character in a string"
published: true
tags: ["JavaScript", "Beginners", "Webdev", "Codenewbie"]
series: JavaScript Katas with miku86
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/0jfyzv0grswtx1mlo17m.jpg
---

## 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](https://www.codewars.com/kata/548ef5b7f33a646ea50000b2)

---

## 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) ⛑

```js
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

```js
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.

- [Explanation 1](https://medium.com/@giltayar/iterating-over-emoji-characters-the-es6-way-f06e4589516)
- [Explanation 2](https://stackoverflow.com/questions/44833008/javascript-counting-frequency-of-emojis-in-text)

Thanks to [Benito van der Zander](https://dev.to/benibela) for commenting!

---

## Implementation (for of-loop) ⛑

```js
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

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

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

---

## Implementation (Functional) ⛑

```js
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

```js
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](https://repl.it/@miku86/js-katas-character-frequency)

---

## 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](https://forms.gle/RmQLq7CLDiD2Ptmw5).

If you want to read my latest stuff, [get in touch with me!](https://miku86.com/newsletter)

---

## Further Reading 📖

- [for-loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for)
- [for of-loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
- [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)

---

## Questions ❔

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