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!