Check if three consecutive elements in an array is identical in JavaScript


We are required to write a JavaScript function, say checkThree() that takes in an array and returns true if anywhere in the array there exists three consecutive elements that are identical (i.e., have the same value) otherwise it returns false.

Therefore, let’s write the code for this function −

Example

const arr = ["g", "z", "z", "v" ,"b", "b", "b"];
const checkThree = arr => {
   const prev = {
      element: null,
      count: 0
   };
   for(let i = 0; i < arr.length; i++){
      const { count, element } = prev;
      if(count === 2 && element === arr[i]){
         return true;
      };
      prev.count = element === arr[i] ? count + 1 : count;
      prev.element = arr[i];
   };
   return false;
};
console.log(checkThree(arr));
console.log(checkThree(["z", "g", "z", "z"]));

Output

The output in the console will be −

true
false

Updated on: 26-Aug-2020

590 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements