Determine overlapping ranges in JavaScript by comparing the "from" and "to" variables for

While working on my angular app, I encountered a seemingly simple task that turned out to be surprisingly complex. I have come up with a few solutions, but none of them seem perfect.
The issue at hand is that I have an array containing possible unlimited(limited) number of [start, end] values, representing number ranges. For example:

    const rangeArr =[[5,10], [15,20], [9,14]];

Now, I need a function that can check for overlaps between any of these ranges. In the given example, the last range [9,14] overlaps with the first one [5,10]

I am currently using a reduce method like this to find an index of an overlapping array:

rangeArr.findIndex((range:[number,number], index: number, arr:[number,number][])=>{
for(let i = 0; i < arr.length-1;i++){
  if(index === i)continue;
  if(range[0]>=arr[index][0] && range[0]<=arr[index][1]){
    return true;
  }
  if(range[1]>=arr[index][0] && range[1]<=arr[index][1]){
    return true;
  }
  return false;
}
})

Although I opted for a traditional approach...I believe there must be a simpler and more concise solution out there...

Answer №1

This function utilizes a linear approach. Feel free to provide input if you require functionality that iterates multiple times:

  function detectOverlap(range1: [number, number], range2: [number, number]): boolean {
    if (range1[0] <= range2[0] && range1[1] >= range2[0]) return true
    if (range1[0] <= range2[1] && range1[1] >= range2[0]) return true
    if (range2[0] <= range1[0] && range2[1] >= range1[0]) return true
    if (range2[0] <= range1[1] && range2[0] >= range1[1]) return true

    return false
  }

  for (let i = 0; i < arrayOfRanges.length - 1; i++) {
    for (let j = i + 1; j < arrayOfRanges.length; j++) {
      if (detectOverlap(arrayOfRanges[i], arrayOfRanges[j])) return true
    }
  }

  return false

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the user hits the enter key, automatically submit a form without the need for

Is it possible to submit a form on enter using type="button"? Here are my input fields: <input type="text" id = "login-user" class="form-control log-input" placeholder="Username" required="required"> <input type="password" id="login-password" clas ...

JavaScript - I have a variable trapped inside a function and I'm struggling to retrieve it

Is it possible that I'm missing something obvious here? I am really struggling to pass the 'body' variable out of this nested function. function retrieveFacebookInfo(userID) { request({ "url": "https://graph.facebook.com/v2.6/" + ...

What steps can be taken to verify values using the console bind function?

Is there a way for developers to check various things in the console while typing code and pressing enter? I attempted to do it but couldn't achieve the desired results. Initially, I added a button on fiddle <button id="test">test< ...

Display invoices for multiple users logged in at the same time using Express.js

I have recently developed an invoice application using the MERN stack. The app works seamlessly when one user is logged in, but issues arise when multiple users try to access it simultaneously. In such cases, the invoices of the first user remain visible t ...

Tips for integrating Google Analytics with React

In my react application, I have various pages: Main Service Contact Profile (private) etc.. To monitor user activity using Google Analytics, I came across the react-ga library which serves the purpose well. However, I find myself having to initialize G ...

Navigating through sections in NextJS-14: Utilizing useRef for seamless scrolling

In the past, I had developed an older portfolio website using Vite React + TS and implemented useRef for scrolling to sections from the Navbar. Now, my goal is to transition this portfolio to NextJS 14. I transferred my old components and style folders in ...

TypeScript declarations for unidentified import statements

I currently have multiple require calls to register middleware in our Express server: app.use('/api/v1/seed_db', ac.allow('ROLE_ADMIN'), require('./routes/seed-db')); app.use('/api/v1/email', require('./routes/ ...

Can arrays be incorporated into HTML scripts using AngularJS?

Below is the HTML code snippet I am working on: <script> Raven.config('___PUBLIC_DSN___', { release: '1.3.0', whitelistUrls: {{urls}}, }).install() </script> This is the controller code snippet: $ ...

Display each column within a single row on an HTML page without extending into the next row

My HTML page layout is structured as follows: https://i.sstatic.net/elwVs.png The issue at hand is that I want the MSAN and Users columns to be in the same row, or else, for a large number of records, it won't be feasible. Here's my HTML file. ...

jQuery link disabling malfunctioning

I attempted to disable a hyperlink by checking a certain condition using an if statement in jQuery. After researching other solutions, I implemented the following code: if (discussionPointsSize == 0) { $('#discussionPointsLink').preventDefault ...

Determining the HTTP method dynamically with Vue Resource

I am trying to dynamically determine the appropriate HTTP method and make a single API call. However, I keep running into an exception when I attempt to call the method. Instead of assuming it's a bug with vue-resource, I believe I may be making a mi ...

Guide to creating a smooth div fade transition with jquery on hover or mouseover

I have a div that is initially set to display:hidden. I am looking to change the display property to display:block when a specific element (#navbar li a) is hovered over. Below is the JavaScript code I have written for this functionality. $('document ...

Execute an AJAX request in JavaScript without using string concatenation

On my webpage, users input code in a programming language which can be over 2000 characters long and include any characters. When they press the send button, the code is sent to a server-side script file using JavaScript AJAX. Currently, I am using the fo ...

Troubleshooting HTML/CSS and JavaScript Issues with Dropdown Menus

I'm having trouble getting my dropdown menu to work properly and I can't figure out why. The JavaScript code should toggle a class that hides the language options and slides up the other tabs like "Contact". However, when I click the button, noth ...

Navigating using JavaScript dot notation is a powerful way to

Is there a way to implement JavaScript or jQuery code that will assign an active class to a dot when it is clicked, while also removing the active class from any other dots in the sequence? HTML: <div class="dotnav"> <div class="dot active" ...

Can an entire object be bound to a model in an Angular controller function?

In TypeScript, I have defined the following Interface: interface Person { Id: number; FirstName: string; LastName: string; Age: number; } Within a .html partial file, there is an Angular directive ng-submit="submit()" on a form element. A ...

Altering the character by striking a key

I have a canvas with custom styling. In the center of the canvas is a single letter. Please see the code below for reference. The goal is to change the displayed letter by pressing a key on the keyboard. For instance: Letter A is centered in the canvas: P ...

Replacing Elements in an Array

Currently, I am working on a JSON/HTML generator project aimed at displaying JSON data along with the associated HTML elements for users once they input the required data into the input fields. Despite identifying the issue, I am struggling to come up with ...

Issue with scrolling in Droppable container on JQuery UI interface

I've encountered an issue with JQuery UI. In my code snippet, I can drag elements onto fields and when hovering over a field, it gets highlighted in green. However, I recently added the functionality to scroll while dragging. Now, I can scroll up and ...

How can I eliminate HTML elements from a string using JavaScript?

Currently, I am utilizing the rich text editor feature of the primeng library. It automatically converts any text I input into HTML format. However, there are instances when I need to display this content in plain text. Is there a straightforward method in ...