
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the First Non-Repeating Character in a String using 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
Advertisements