Generating dynamic arrays in JavaScript

View the working code here: http://jsfiddle.net/sXbRK/

I have multiple line segments with unique IDs, and I know which ones intersect.

My goal is to create new arrays that only contain the IDs of the overlapping line segments.

I do not need the IDs of line segments that do not intersect each other.

Can anyone provide guidance on how to achieve this? How can I populate separate arrays with IDs of intersecting line segments?

// Example of new arrays containing overlapping IDs
e.g. Array A = [1, 2, 3];
     Array B = [7, 8, 12];
     Array C = [14, 15];

Here is my current approach, and make sure to refer to the work-in-progress code on jsFiddle:

function findIntersections(lineSegments) {
    var len = lineSegments.length;
    
    for (var a = 0; a < len - 1; a++) {
        for (var b = a + 1; b < len; b++) {
            var segmentA = lineSegments[a],
                segmentB = lineSegments[b],
                overlappingIDs = [];
            
            if ((segmentA.start <= segmentB.start && (segmentA.start + segmentA.end) >= segmentB.start) || 
                (segmentA.start <= segmentB.start && (segmentB.start + segmentB.end) >= segmentA.start)) {
                // Add intersecting IDs to array
                overlappingIDs.push(segmentA.id, segmentB.id);
            }
        }
    }
}

// Test data
var lineSegments = [
    {id:'1', start:0, end:50},
    {id:'2', start:0, end:50},
    {id:'3', start:0, end:50},
    {id:'4', start:100, end:50},
    {id:'5', start:200, end:50},
    {id:'6', start:300, end:50},
    {id:'7', start:900, end:50},
    {id:'8', start:900, end:50},
    {id:'9', start:600, end:50},
    {id:'10', start:700, end:50},
    {id:'11', start:800, end:50},
    {id:'12', start:900, end:50},
    {id:'13', start:1000, end:50},
    {id:'14', start:1100, end:50},
    {id:'15', start:1100, end:50}
];

// Execute the function
findIntersections(lineSegments);

Any suggestions or ideas would be greatly appreciated. Thank you!

Answer №1

Give it a shot:

var lineSegments = [
    {id:'1',  start:0,    end:50},
    {id:'2',  start:0,    end:50},
    {id:'3',  start:0,    end:50},
    {id:'4',  start:100,  end:50},
    {id:'5',  start:200,  end:50},
    {id:'6',  start:300,  end:50},
    {id:'7',  start:900,  end:50},
    {id:'8',  start:900,  end:50},
    {id:'9',  start:600,  end:50},
    {id:'10', start:700,  end:50},
    {id:'11', start:800,  end:50},
    {id:'12', start:900,  end:50},
    {id:'13', start:1000,  end:50},
    {id:'14', start:1100,  end:50},
    {id:'15', start:1100,  end:50}
];


function fixDirectionality(line) {
   if (line.start > line.end) {
     var temp = line.start;
     line.start = line.end;
     line.end = temp;
   }
   return line;
}

function findIntersectingLines(lines) {
  var lineA, lineB;
  var intersectedLines = [], combinedPairs = [];

  // for each line
  for (var i=0, len=lines.length - 1; i<len; i++) {
    lineA = fixDirectionality(lines[i]);

    // for every other line
    for (var j=i+1, jLen=lines.length; j<jLen; j++) {
      lineB = fixDirectionality(lines[j]);

      if (  (lineA.start <= lineB.start && lineA.end >= lineB.end) ||
            (lineA.start <= lineB.start && lineA.end >= lineB.end) ||
            (lineA.start <= lineB.end && lineA.end >= lineB.end) ) {
        intersectedLines.push(lineA.id, lineB.id);
        combinedPairs.push([lineA.id, lineB.id]);
      }
    }
  }

  console.log('combinedPairs: ' + combinedPairs);

}

findIntersectingLines(lineSegments);

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

How require works in Node.js

My current database connection module looks like this: var mongodb = require("mongodb"); var client = mongodb.MongoClient; client.connect('mongodb://host:port/dbname', { auto_reconnect: true }, function(err, db) { if (err) { ...

What are the specific extensions for email validation?

code for the form: <form class="form" name ="custRegistration" id="custRegistration" onsubmit="return submitAlbum(this)" action="download.jsp" method="post" > <p class="email"> <label for="budget">Expected Budget ...

No matter what I do, I can't seem to stop refreshing the page. I've attempted to prevent default, stop propagation, and even tried using

Below is the code I have written for a login page: import { useState } from "react"; import IsEmail from "isemail"; import { useRouter } from "next/router"; import m from "../library/magic-client"; import { useEffect ...

The $or operator in mongoose falls short in providing complete data when paired with the find() method

I am currently utilizing the find method in conjunction with the $or operator to search the database for any duplicate data within this specific line. const duplicate = await NewItemsData.find({ $or: newItems }); Upon inspecting the variable in the consol ...

How can I conceal child <div> elements when the parent div is resized?

Struggling to implement a zoom in/out feature on my web app using the jqueryUI slider. Having trouble handling cases where the parent div shrinks too much, causing issues with the child containers. <div class="puck originator inline-block" style="w ...

Sending data to a React component from regular HTML

I have a question about implementing a method to pass custom attributes from HTML elements as props to React components. Here's an example: function someFunction(props) { return <h1>props.something</h1> } HTML: <div id="someEl ...

Tips for implementing Papa Parse to parse CSV files using JavaScript

I've been exploring their API without much luck. My goal is to extract data from CSV files that are sent to the client upon server entry. Here's the code snippet I attempted: // Attempting to parse local CSV file Papa.parse("data/premier leagu ...

Utilizing Local Storage in Vuex Store with Vue.js

I have been working with localStorage for storing and retrieving items in my JavaScript code housed within a .vue file. However, I am now looking to find a way to transfer this stored data into my Vuex store, specifically within the mutations section locat ...

reveal the concealed divs within the list elements

html: In my HTML document, I have a unordered list (ul) with each list item (li) constructed like this: <li class="A">list-item <div>1</div> <div class="B">2 <div class="C">3</div> </div> ...

Executing a protractor test on Safari results in the message "Angular was not located on the webpage https://angularjs.org/"

Recently, I encountered an issue while trying to run a Protractor test on Safari, even when following the official example provided at http://www.protractortest.org/. Below are my conf.js and todo-spec.js files. The problem arises when I set browser.ignor ...

Certain hyperlinks are refusing to open within an embedded iframe

I'm currently facing an issue with finding a solution for a simple problem. I am in the process of developing a portfolio plugin and one of the requirements is to showcase projects within an iframe to demonstrate their responsive layout. However, I&ap ...

What is the best method for eliminating the initial character in every line of a textarea?

The desired output should display as LUNG,KIDNEY,SKELETON>J169>U and E, CREATININE:no instead of >LUNG,KIDNEY,SKELETON>J169>U and E, CREATININE:no. Is there a way to achieve this using JavaScript? Specifically, the ">" character at the be ...

Guide on creating an AJAX request for a POST method

I am new to working with AJAX, and I have been trying to use it for a POST function similar to the curl command below: curl -X POST -H 'Content-type:application/json' --data-binary '{ "replace-field":{ "name":"sell-by", "type":"date", " ...

Challenges in finding solutions from the generated results

I'm relatively new to Java and I'm struggling to prepare for an upcoming exam. One of the questions asks to explain the exact output generated by the given code: public class Lab7Experiment extends JApplet { int x=3, y=-3, z=5; int someV ...

How can I incorporate eventData when using .bind() for the "keydown" event type?

I want to achieve something like this: var keydownHandler = function (ev) { alert(ev.data.test); return false; } $(document).bind('keydown', {test: 'foo'}, keydownHandler); However, the .bind method doesn't seem to be wor ...

Serialize a form while keeping the submitted data private

Is there a way to achieve serialization without triggering the submit function for an ajax call? I've searched extensively for a solution to this issue without any luck. The java script function is invoked when a button within the form is clicked. do ...

Leveraging AJAX Post Data in NodeJS using Express

I'm currently working on retrieving the values I send for an ajax post within my node application. After referring to a helpful post on Stack Overflow, here is what I have implemented so far: Within Node.js: var express = require('express&apos ...

What is the best way to transfer information to a different component using Vue router?

At the moment, I have a component that is displayed on the page. When I check the this.$router variable inside this component, I notice that the full path property is '/hello/reports?report=3849534583957' and the path property is '/hello/rep ...

Leveraging underscore.js for null verification

let name = "someName"; if(name !== null) { // perform some action } Currently, I am utilizing http://underscorejs.org/#isNull. How can I achieve the same functionality using underscore.js? Is there any noticeable performance enhance ...

Execute a Node script using PHP exec, retrieve the data in PHP, and then apply the finally method

I'm working on a PHP script that utilizes the exec function to run a Node script and then return some data back to the PHP script. The challenge I'm facing is finding a way to send the data back to PHP without having to wait for the cleanup code ...