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 : 1;
        prev.element = arr[i];
    };
    return false;
};
console.log(checkThree(arr));
console.log(checkThree(["z", "g", "z", "z"]));

Output

true
false

Alternative Approach Using Simple Loop

Here's a more straightforward approach that directly checks three consecutive elements:

const checkThreeSimple = arr => {
    for(let i = 0; i <= arr.length - 3; i++){
        if(arr[i] === arr[i + 1] && arr[i + 1] === arr[i + 2]){
            return true;
        }
    }
    return false;
};

// Test cases
console.log(checkThreeSimple(["a", "b", "b", "b", "c"])); // true
console.log(checkThreeSimple(["a", "b", "c", "d", "e"])); // false
console.log(checkThreeSimple([1, 1, 2, 2, 2, 3]));       // true
true
false
true

How It Works

The first approach uses a tracking object to count consecutive identical elements. When the count reaches 2 and the next element matches, we have found three consecutive identical elements.

The second approach directly compares three consecutive elements at each position, which is more intuitive and efficient for this specific problem.

Conclusion

Both methods effectively detect three consecutive identical elements in an array. The simple loop approach is more readable and efficient for this specific use case.

Updated on: 2026-03-15T23:18:59+05:30

899 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements