Check If Three Consecutive Elements in an Array Are 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: 2020-08-26T11:10:32+05:30

761 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements