Start learning free

LESSON 224 OF 285 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Word Frequency in JavaScript: Split a Sentence and Count

Practice Read the full explanation

Given a string sentence, count how many times each word appears in it. Return a dictionary where each word of the sentence is a key, and its value is the number of times that word appears.

The words are in lower case and separated by single spaces, and the sentence has at least one word. The order of the entries doesn't matter.

Example 1:

Input: sentence = "the cat and the hat"
Output: {"the": 2, "cat": 1, "and": 1, "hat": 1}
Explanation: "the" appears twice. Every other word appears once.

Example 2:

Input: sentence = "go go go"
Output: {"go": 3}
Explanation: The same word three times gives one key, "go", with the value 3.

Example 3:

Input: sentence = "hello"
Output: {"hello": 1}
Explanation: A sentence of one word: that word appears once.
STEP 1 OF 6
    Ctrl + Enter to check

    JAVASCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Frequency in JavaScript, explained

    Problem overview

    The method wordFrequency(sentence) receives a sentence of lowercase words separated by single spaces. It returns an object that maps each word to how many times it appears.

    For "the cat and the hat" the result is {"the": 2, "cat": 1, "and": 1, "hat": 1}. For "go go go" it is {"go": 3}: three occurrences, one key.

    Approach

    The task has two parts. First, turn the sentence into an array of words. Second, count them with a dictionary, using the same pattern as counting letters: if the word already has a key, add 1; otherwise create it with the value 1.

    The only new piece is splitting. Because the words are separated by exactly one space, cutting the string at every space gives exactly the words.

    Step by step

    1. Split the sentence with sentence.split(" ") and store the array in words.
    2. Create an empty object named counts, declared with const.
    3. Loop over the words with for...of.
    4. Increase the count of a word that is already a key: counts[word] += 1.
    5. Start new words at 1 in the else branch.
    6. Return counts after the loop.

    The solution in JavaScript

    class Solution {
        wordFrequency(sentence) {
            const words = sentence.split(" ");
            const counts = {};
            for (let word of words) {
                if (word in counts) {
                    counts[word] += 1;
                } else {
                    counts[word] = 1;
                }
            }
            return counts;
        }
    }
    

    What to know about the language here:

    • split returns an array of strings. "the cat and the hat".split(" ") gives ["the", "cat", "and", "the", "hat"], and a one-word sentence such as "hello" gives ["hello"], an array with one item.
    • A missing key reads as undefined, and undefined + 1 is NaN. The else branch exists so that the first count is 1 and not NaN.
    • Objects inherit names. Every plain object inherits properties such as constructor and toString, and the in operator sees them: "constructor" in {} is true. For the sentence "constructor" the function does not return {constructor: 1}. It returns an object whose constructor value is the text "function Object() { [native code] }1", because the branch that adds 1 runs on the inherited function. A Map, or an object made with Object.create(null), avoids this. For the lowercase everyday words in this lesson the pattern works as written.

    Tracing the examples

    For "the cat and the hat", the loop meets "the" (new, count 1), "cat" (new), "and" (new), "the" again (count becomes 2) and "hat" (new). The final object is {the: 2, cat: 1, and: 1, hat: 1}.

    For "go go go", "go" is created with 1 on the first pass and then grows to 2 and 3, so the result is {go: 3}.

    Complexity

    Time: O(n), where n is the length of the sentence. split reads each character once to build the array, and then the loop visits each word once. Every check and update on the object takes constant time on average.

    Space: O(n) in the worst case. The array of words holds every word, and the object holds one key per different word, which is as many as the words when none repeats.

    Using the result

    With the counts in hand, other questions become short loops. For the frequencies of "the cat and the hat", Object.keys(counts) is ["the", "cat", "and", "hat"], the different words, and Object.values(counts) is [2, 1, 1, 1]. Adding the values gives 5, the number of words in the sentence. Scanning the object for the largest value finds the most common word, which is "the".

    The alternative, with no dictionary, would count each word by scanning the whole array for its repeats. That repeats work for every word and takes time proportional to the square of the number of words. The dictionary makes one pass instead, and that is the point of the exercise: a dictionary turns "have I seen this before?" into a single quick lookup.

    Case and punctuation

    The lesson promises lower case and single spaces, so the function does no cleanup. Real text needs more. "The cat".split(" ") gives ["The", "cat"], and "The" and "the" would be two separate keys unless you call toLowerCase() on the sentence first. Punctuation attached to a word, such as a trailing comma, would also make a different key. Those cases need extra steps before the counting loop, and the counting loop itself stays the same.

    Other ways to write it

    The if/else form shows both cases clearly. The same count can be written on one line:

    counts[word] = (counts[word] ?? 0) + 1;
    

    This also reads an inherited name as present, so for the sentence "constructor" it gives the same odd result as the lesson's code. A Map doesn't have the problem: map.set(word, (map.get(word) ?? 0) + 1) gives Map(1) {'constructor' => 1}. For the sentences in this lesson, a plain object is the expected return value, so use the object and keep the Map in mind for arbitrary text.

    Edge cases and common mistakes

    • Splitting on the wrong character. split("") cuts between every character and gives letters. The separator must be a space, " ".
    • Forgetting the first-time branch. Without it, every count is NaN.
    • Extra spaces. The lesson promises single spaces. With two spaces in a row, split(" ") produces an empty string between them, and that empty string would be counted as a word: "a b" would produce an entry with the empty key.
    • One word. "hello" gives {hello: 1}.

    Testing

    • "the cat and the hat" gives {the: 2, cat: 1, and: 1, hat: 1}.
    • "go go go" gives {go: 3}.
    • "hello" gives {hello: 1}.
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free