JavaScript Remove non-duplicate characters from string

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a JavaScript function that takes in a string and returns a new string with all non-duplicate characters removed from it.

For example −

If the input string is −

"teeth_foot"

Then the output should be −

"teetoot"

Therefore, let's write the code for this function −

Example

const str = 'teeth_foot';
const removeNonDuplicate = str => {
   const strArray = str.split("");
   const duplicateArray = strArray.filter(el => {
      return strArray.indexOf(el) !== strArray.lastIndexOf(el);
   });
   return duplicateArray.join("");
};
console.log(removeNonDuplicate(str));

Output

The output in the console will be −

teetoot
raja
Published on 31-Aug-2020 10:27:24
Advertisements