Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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:
- Split the string into an array of words
- Identify words that appear multiple times
- Collect unique duplicates preserving first occurrence order
- 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.
Advertisements
