Finding first non-repeating character JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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 −


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]){
            return ind;
         count = 0;
      } else {
   return -1;


The output in the console will be −

Published on 31-Aug-2020 10:18:57