Combining intersecting objects with interval attributes in an array using javascript

I have encountered similar questions, however, the provided answers do not resolve my specific issue.

The data I have is an array of range objects, each with the following properties:

  • start: Integer, indicating the start of the range,
  • end: Integer, indicating the end of the range.

The desired output is:

An array of non-overlapping range objects that cover the same ranges as the input, sorted from the smallest start to the largest start. Two ranges do not overlap if:

  • range1.start <= range2.start, and
  • range1.end >= range2.start

Input:

[
  { start: 8, end: 10 },
  { start: 5, end: 7  },
  { start: 9, end: 12 },
  { start: 2, end: 6  },
]

Output:

 [
   { start: 2, end: 7  },
   { start: 8, end: 12 }
 ]

I have attempted various solutions found online for merging overlapping intervals, but they have not provided the desired result.

Thank you.

Answer №1

To efficiently handle overlapping ranges, one approach is to sort the array based on the start and end values. Then, iterate through the sorted array and check for any overlapping ranges.

var data = [{ start: 8, end: 10 }, { start: 5, end: 7 }, { start: 9, end: 12 }, { start: 2, end: 6 }],
    result = data
        .sort(function (a, b) { return a.start - b.start || a.end - b.end; })
        .reduce(function (r, a) {
            var last = r[r.length - 1] || [];
            if (last.start <= a.start && a.start <= last.end) {
                if (last.end < a.end) {
                    last.end = a.end;
                }
                return r;
            }
            return r.concat(a);
        }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

var intervals = [
  { start: 8, end: 10 },
  { start: 5, end: 7  },
  { start: 9, end: 12 },
  { start: 2, end: 6  }
];


function mergeIntervals(intervals) {
  // sort the intervals based on start value
  intervals.sort((a, b) => a.start - b.start);
  
  // function to merge two intervals
  var mergeFn = (a, b) => ({start: Math.min(a.start, b.start), end: Math.max(a.end, b.end)});
  
  // function to check if two intervals overlap
  var overlapFn = (a, b) => (b.start <= a.end);
  
  var current = intervals[0];
  var result = [];
  for(var i = 1; i < intervals.length; i++) {
    if(overlapFn(current, intervals[i])) 
       current = mergeFn(current, intervals[i]);
    else {
      result.push(current);
      current = intervals[i];
    }
  }
  result.push(current);

  return result;
}

console.log(mergeIntervals(intervals));

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

Can you explain the concepts of 'theme' and 'classes'?

Currently, I am working on a web application using React. I have chosen to incorporate the latest version of Material-UI for designing the user interface. During this process, I came across the demo examples provided by Material-UI (like ) In each demo ...

Unable to load module/controller file from Angular 1 into view/html

var app = angular.module("appModule",[]); app.controller("viewController",function($scope){ $scope.greeting = "Welcome to the future"; }); <html> <head> <script src="Scripts/script.js"></script> <script ...

A step-by-step guide on how to use ajax/jquery to access an external webpage without relying on iframe

Is there a more effective way to call another page, such as http://www.google.com, and load it into my specific div without using an iframe? I attempted to do so with ajax... $.ajax({ url : 'http://www.google.com', success : function ( ...

The anchor link is not aligning properly due to the fluctuating page width

Seeking help to resolve an issue I'm facing. Maybe someone out there has a solution? The layout consists of a content area on the left (default width=70%) and a menu area on the right (default width=30%). When scrolling down, the content area expand ...

Tips for passing a parameter (such as an ID) through a URL using ng-click to display a subdocument belonging to a particular user in

I am looking to retrieve specific user subdocument data on a separate page by passing the id parameter in a URL using ng-click in AngularJS. <tr ng-repeat="register in registerlist | filter:searchText"> <td>{{$index+1}}</td> <td&g ...

How to resolve the issue of not being able to access functions from inside the timer target function in TypeScript's

I've been attempting to invoke a function from within a timed function called by setInterval(). Here's the snippet of my code: export class SmileyDirective { FillGraphValues() { console.log("The FillGraphValues function works as expect ...

Recording audio using Cordova and Javascript

Recently, I've been dabbling in creating a new app using Cordova, VueJs, and Onsen UI for VueJs. One of the main features I want to implement is the ability to use the microphone on Android or iOS devices to record audio and then send it to the Google ...

Using Typescript to import an npm package that lacks a definition file

I am facing an issue with an npm package (@salesforce/canvas-js-sdk) as it doesn't come with a Typescript definition file. Since I am using React, I have been using the "import from" syntax to bring in dependencies. Visual Studio is not happy about th ...

Material UI: Easily adjusting font size within Lists

When developing forms with react js and material UI, I encountered an issue with changing the font size within lists to achieve a more compact layout. The code fontSize={10} didn't seem to have any effect regardless of where I added it. Is there a wa ...

Utilizing nested JSON data with React

Hey there! I've been working on adding more levels in Json pulled from Mongo, but I'm running into an issue with accessing elements that have multiple levels of nesting. It seems like it can't read the undefined property. Is there a limit t ...

Listening to sound from a specific table cell retrieved from an array generated by a Struct

I'm working on a project where I have a table displaying ambient sounds. When you click on a sound, it takes you to another view controller that shows the sound title, an image, description, and a play button. All the data is stored in an array inside ...

Leveraging the (click) event within an HTML template to manage a [hidden] element located in a different template using Angular 2

Within my project, I have two TypeScript files, each containing HTML templates inside the @Component. In one of the templates, there are info cards that can be collapsed or expanded using [hidden]="collapsed". The following function is present in both file ...

Unlocking the potential of GraphQL: Harnessing the power of sibling resolvers to access output from another

Could use a little assistance. Let's say I'm trying to retrieve the following data: { parent { obj1 { value1 } obj2 { value2 } } } Now, I need the result of value2 in the value1 resolver for calculation ...

Steps for checking if the specified row has been accurately filled out in a loop

Here is an example of how my JSON data is structured: { "main_object": { "id": "5", "getExerciseTitle": "TestFor", "language": "nl_NL", "application": "lettergrepen", "main_object": { "title": "TestFor", "language": "nl_NL", "exercises": [ { ...

I'm facing a challenge with retrieving the controller's scope in my Angular directive

Having trouble accessing the settings I receive from the server in my app. The directives are set up correctly and the $http is used to fetch a js file with the app settings. However, despite being able to log the scope in the console, I am unable to acces ...

Utilize JavaScript to seamlessly play a Spotify track within the Spotify client without disrupting your current

A little while back, I recall the simplicity of clicking play on a song within a website and having it instantly start playing on my computer without any additional steps. It was seamless and effortless. My goal for my website is to have music start playi ...

passing parameters via routes

I've been working on passing parameters through the URL using this code, but it doesn't seem to be functioning properly. I suspect that the issue lies in the "get(\users:id)" part, but I'm unsure of the correct way to do it: $.ajax ...

Concealing an Automatically Updated Section when Devoid of Content -- Ruby on Rails Version 4

I have come across various solutions to this problem, but none of them seem to be effective for my specific project. In my application, the user's previous choices are displayed in multiple divs. Initially, all the divs are empty. As the user progress ...

Confirm that the input into the text box consists of three-digit numbers separated by commas

Customers keep entering 5 digit zip codes instead of 3 digit area codes in the telephone area code textbox on my registration form. I need a jQuery or JavaScript function to validate that the entry is in ###,###,###,### format without any limit. Any sugge ...

React Native Issue: Missing propType for native property RCTView.maxHeight

Upon upgrading to RN 0.30, I encountered the error message below even when trying to build the most basic app: react-native init AwesomeProject react-native run-ios What's peculiar is that the warnings include components BlurView, VibrancyView, an ...