How to use an Object In Javascript
In this approach, we use an object to track the frequency of each word. We iterate over each word in the array of words. For each word, we check if the object already has the word as a key. If the word is found, we return it as the first repeated word. Otherwise, we add it to the object with a count.
Example: The below example uses an object to find the first repeated word in a string.
function findFirstRepeatedWord(str) {
const words = str.split(' ');
const wordCount = {};
for (let word of words) {
if (wordCount[word]) {
return word;
} else {
wordCount[word] = 1;
}
}
return "No Repetition";
}
const str = "Ravi had been saying that he had been there";
const repeatedWord = findFirstRepeatedWord(str);
console.log(repeatedWord);
Output
had
JavaScript Program to Find the First Repeated Word in String
Given a string, our task is to find the 1st repeated word in a string.
Examples:
Input: “Ravi had been saying that he had been there”
Output: had
Input: “Ravi had been saying that”
Output: No Repetition
Below are the approaches to Finding the first repeated word in a string:
Table of Content
- Using Set
- Using indexOf method
- Using Nested for loop
- Using a Map
- Using an Object