Keeping only redundant words in a string in JavaScript

We are required to write a JavaScript function that takes in a string and returns a new string with only the words that appeared more than once in the original string.

Problem Statement

If the input string is:

const str = 'this is a is this string that contains that some repeating words';

Then the output should be:

'this is that'

The function should identify duplicate words and return them in the order they first appeared.

Using indexOf() and lastIndexOf()

This approach checks if a word's first occurrence differs from its last occurrence, indicating duplicates:

const str = 'this is a is this string that contains that some repeating words';

const keepDuplicateWords = str => {
    const strArr = str.split(" ");
    const res = [];
    
    for(let i = 0; i < strArr.length; i++){
        if(strArr.indexOf(strArr[i]) !== strArr.lastIndexOf(strArr[i])){
            if(!res.includes(strArr[i])){
                res.push(strArr[i]);
            }
        }
    }
    return res.join(" ");
};

console.log(keepDuplicateWords(str));
this is that

Using Map for Word Counting

A more efficient approach using a Map to count word occurrences:

const str = 'this is a is this string that contains that some repeating words';

const keepDuplicateWordsMap = str => {
    const words = str.split(" ");
    const wordCount = new Map();
    
    // Count occurrences
    words.forEach(word => {
        wordCount.set(word, (wordCount.get(word) || 0) + 1);
    });
    
    // Filter words that appear more than once, preserve order
    const duplicates = words.filter((word, index, arr) => 
        wordCount.get(word) > 1 && arr.indexOf(word) === index
    );
    
    return duplicates.join(" ");
};

console.log(keepDuplicateWordsMap(str));
this is that

Comparison

Method Time Complexity Space Complexity Readability
indexOf/lastIndexOf O(n²) O(n) Simple
Map counting O(n) O(n) More complex

How It Works

Both methods:

  1. Split the string into an array of words
  2. Identify words that appear multiple times
  3. Collect unique duplicates preserving first occurrence order
  4. Join the results back into a string

Conclusion

The Map approach is more efficient for large strings, while the indexOf method is simpler to understand. Both preserve the original order of duplicate words' first appearances.

Updated on: 2026-03-15T23:19:00+05:30

472 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements