
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
Checking for Overlapping Times in JavaScript
We are required to write a JavaScript function that takes in an array of intervals (start and end time like this −
const arr = [ { start: '01:00', end: '04:00' }, { start: '05:00', end: '08:00' }, { start: '07:00', end: '11:00' }, { start: '09:30', end: '18:00' }, ];
Our function should iterate through this array of objects and check all elements of the array against the others.
If an overlapping interval is found, the iteration stops and true is returned, Otherwise false. By overlapping intervals, we mean time intervals that have some time in common.
Example
const arr = [ { start: '01:00', end: '04:00' }, { start: '05:00', end: '08:00' }, { start: '07:00', end: '11:00' }, { start: '09:30', end: '18:00' }, ]; const overlapping = (a, b) => { const getMinutes = s => { const p = s.split(':').map(Number); return p[0] * 60 + p[1]; }; return getMinutes(a.end) > getMinutes(b.start) && getMinutes(b.end) > getMinutes(a.start); }; const isOverlapping = (arr) => { let i, j; for (i = 0; i < arr.length - 1; i++) { for (j = i + 1; j < arr.length; j++) { if (overlapping(arr[i], arr[j])) { return true; } }; }; return false; }; console.log(isOverlapping(arr));
Output
And the output in the console will be −
true
Advertisements