Checking for uniqueness of a string in JavaScript


We are required to write a JavaScript function that takes in a string as the first and the only argument. The function should return true if all the characters present in the string are unique. And if even one character appears for more than one, the function should return false.

We will use a hash set to keep track of the characters we encounter in the string and if at any stage of iteration, we encounter duplicate characters, we will return false otherwise at the end of iteration, we will return true.

Example

Following is the code −

const str = 'abschyie';
const checkUniqueness = (str = '') => {
   const hash = new Set();
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(hash.has(el)){
         return false;
      };
      hash.add(el);
   };
   return true;
};
console.log(checkUniqueness(str));

Output

Following is the console output −

true

Updated on: 23-Jan-2021

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements