Twice repetitive word count in a string - JavaScript

We are required to write a JavaScript function that takes in a string that contains some words that are repeated twice, we need to count such words.

For example, if the input string is:

const str = "car bus jeep car jeep bus motorbike truck";

Then the output should be:

3

The function counts words that appear more than once in the string. In this case, "car", "bus", and "jeep" each appear twice.

Using Array Methods

Here's a solution that splits the string into words and counts duplicates:

const str = "car bus jeep car jeep bus motorbike truck";

const countRepetitive = str => {
    const strArr = str.split(" ");
    let count = 0;
    for(let i = 0; i < strArr.length; i++){
        if(i === strArr.lastIndexOf(strArr[i])){
            continue;
        };
        count++;
    };
    return count;
};

console.log(countRepetitive(str));
3

How It Works

The algorithm works by:

  • Splitting the string into an array of words using split(" ")
  • Iterating through each word's position
  • Using lastIndexOf() to find the last occurrence of each word
  • If the current index equals the last index, the word appears only once
  • Otherwise, increment the count for repeated words

Alternative Method Using Map

A cleaner approach using a Map to count word frequencies:

const str = "car bus jeep car jeep bus motorbike truck";

const countRepetitiveWithMap = str => {
    const words = str.split(" ");
    const wordCount = new Map();
    
    // Count frequency of each word
    words.forEach(word => {
        wordCount.set(word, (wordCount.get(word) || 0) + 1);
    });
    
    // Count words that appear more than once
    let duplicateCount = 0;
    for (let [word, count] of wordCount) {
        if (count > 1) {
            duplicateCount += count;
        }
    }
    
    return duplicateCount;
};

console.log(countRepetitiveWithMap(str));
6

Note: This version counts total occurrences of repeated words, not unique repeated words.

Counting Unique Repeated Words

To count only unique words that are repeated:

const str = "car bus jeep car jeep bus motorbike truck";

const countUniqueRepeated = str => {
    const words = str.split(" ");
    const wordCount = new Map();
    
    words.forEach(word => {
        wordCount.set(word, (wordCount.get(word) || 0) + 1);
    });
    
    let uniqueRepeatedCount = 0;
    for (let count of wordCount.values()) {
        if (count > 1) {
            uniqueRepeatedCount++;
        }
    }
    
    return uniqueRepeatedCount;
};

console.log(countUniqueRepeated(str));
3

Conclusion

The original method efficiently counts repeated words using array indexing. The Map-based approach offers better readability and can be easily modified to count different repetition patterns.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements