

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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
- Related Questions & Answers
- Finding first non-repeating character JavaScript
- Finding the index of the first repeating character in a string in JavaScript
- First non-repeating character using one traversal of string in C++
- Return index of first repeating character in a string - JavaScript
- Detecting the first non-repeating string in Array in JavaScript
- Find the first non-repeating character from a stream of characters in Python
- How to find its first non-repeating character in a given string in android?
- Find first repeating character using JavaScript
- Find the last non repeating character in string in C++
- Python program to Find the first non-repeating character from a stream of characters?
- Java program to Find the first non-repeating character from a stream of characters
- Finding the largest non-repeating number in an array in JavaScript
- Queries to find the last non-repeating character in the sub-string of a given string in C++
- First non-repeating in a linked list in C++
- Finding the first non-consecutive number in an array in JavaScript
Advertisements