
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
Finding First Non-Repeating Character in JavaScript
We have an array of Numbers/String literals where most of the entries are repeated. Our job is to write a function that takes in this array and returns the index of first such element which does not make consecutive appearances.
If there are no such elements in the array, our function should return -1. So now, let's write the code for this function. We will use a simple loop to iterate over the array and return where we find non-repeating characters, if we find no such characters, we return -1 −
Example
const arr = ['d', 'd', 'e', 'e', 'e', 'k', 'j', 'j', 'h']; const firstNonRepeating = arr => { let count = 0; for(let ind = 0; ind < arr.length-1; ind++){ if(arr[ind] !== arr[ind+1]){ if(!count){ return ind; }; count = 0; } else { count++; } }; return -1; }; console.log(firstNonRepeating(arr));
Output
The output in the console will be −
5
Advertisements