Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Filter 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 −

 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
Updated on: 2021-04-17T11:49:16+05:30

736 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements