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