We are required to write a JavaScript function that takes in a string and returns a new string with only the words that appeared for more than once in the original string.
For example: If the input string is −
const str = "big black bug bit a big black dog on his big black nose";
Then the output should be −
const output = "big black";
Example
Let’s write the code for this function −
const str = "big black bug bit a big black dog on his big black nose"; const findDuplicateWords = 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(findDuplicateWords(str));
Output
The output in the console: −
big black