Filtering string to contain unique characters in JavaScript

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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
raja
Published on 17-Apr-2021 11:43:08
Advertisements