
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements