Finding the first non-repeating character 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 find and return the index of first character it encounters in the string which appears only once in the string.

If the string does not contain any unique character, the function should return -1.

For example −

If the input string is −

const str = 'hellohe';

Then the output should be −

const output = 4;

Example

Following is the code −

const str = 'hellohe';
const firstUnique = (str = '') => {
   let obj = {};
   for(let i = 0; i < str.length; i++){
      if(str[i] in obj){
         let temp = obj[str[i]];
         let x = parseInt(temp[0]);
         x += 1;
         temp[0] = x;
         obj[str[i]] = temp;
      } else {
         obj[str[i]] = [1, i]
      }
   }
   let arr = Object.keys(obj);
   for(let i = 0; i < arr.length; i++){
      let z = obj[arr[i]]
      if(z[0] === 1){
         return z[1];
      }
   }
   return -1;
};
console.log(firstUnique(str));

Output

Following is the console output −

4

Updated on: 20-Jan-2021

340 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements