Computer >> Computer tutorials >  >> Programming >> Javascript

Filtering string to contain unique characters in JavaScript


Problem

We are required to write a JavaScript function that takes in a string str. Our function should construct a new string that contains only the unique characters from the input string and remove all occurrences of duplicate characters.

Example

Following is the code −

const str = 'hey there i am using javascript';
const removeAllDuplicates = (str = '') => {
   let res = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(str.indexOf(el) === str.lastIndexOf(el)){
         res += el;
         continue;
      };
   };
   return res;
};
console.log(removeAllDuplicates(str));

Output

Following is the console output −

Ymungjvcp