Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding duplicate "words" in a string - 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 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
Advertisements