
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Check if array elements are consecutive in Python
- How to check if array contains three consecutive dates in java?
- Three strictly increasing numbers (consecutive or non-consecutive). in an array in JavaScript
- Check if items in an array are consecutive but WITHOUT SORTING in JavaScript
- Check three consecutive numbers - JavaScript
- Python – Consecutive identical elements count
- Consecutive elements sum array in JavaScript
- Sum identical elements within one array in JavaScript
- JavaScript to check consecutive numbers in array?
- Python - Check if all elements in a list are identical
- Check if Queue Elements are pairwise consecutive in Python
- Finding three elements with required sum in an array in JavaScript
- How do we check if an object is an array in Javascript?
- Adding up identical elements in JavaScript
- How to check if a variable is an array in JavaScript?

Advertisements