Finding first unique element in sorted array in JavaScript

JavascriptWeb DevelopmentObject Oriented ProgrammingFront End Technology

Suppose, we have a sorted array of literals like this −

const arr = [32, 32, 63, 63, 63, 75, 75, 86, 87, 88, 89];

We are required to write a JavaScript function that takes in one such array and returns the first unique number in the array.

If there is no such number in the array, our function should return false.

For this array, the output should be 86.

The code for this will be −

const arr = [32, 32, 63, 63, 63, 75, 75, 86, 87, 88, 89];
const firstUnique = arr => {
   let appeared = false;
   for(let i = 0; i < arr.length; i++){
      if(appeared){
         if(arr[i+1] !== arr[i]){
            appeared = false;
         };
      }else{
         if(arr[i+1] === arr[i]){
            appeared = true;
            continue;
         };
         return arr[i];
      };
   };
   return false;
};
console.log(firstUnique(arr));

Following is the output on console −

86
raja
Published on 09-Oct-2020 11:29:14
Advertisements