var items = [
{"id": 1, "begin":10, "end":30},
{"id": 2, "begin":20, "end":40},
{"id": 3, "begin":30, "end":50},
{"id": 4, "begin":40, "end":60},
{"id": 5, "begin":50, "end":70},
{"id": 6, "begin":100, "end":170},
{"id": 7, "begin":120, "end":180}
];
for (var i = 0; i < items.length; i++) {
var currBegin = items[i].begin;
var currEnd = items[i].end;
var out = [];
for (var j = 0; j < items.length; j++) {
var innerBegin = items[j].begin;
var innerEnd = items[j].end;
if (innerBegin < currBegin && innerEnd < currEnd && innerEnd >= currBegin)
out.push(items[j].id);
}
console.log(out)
}
I’m trying to check if numbers overlap each other based on an initial and end number.
So far my code is giving the wrong output: http://jsfiddle.net/bZzSV/
[]
[1]
[1, 2]
[2, 3]
[3, 4]
[]
[6]
Basically check if an element overlaps with another. 1,2 overlap, but 1,3 doesn’t, however 2,3 does… at the end, 1-5 are overlapped because of those links.
I would like to output:
[1, 2, 3, 4, 5]
[6, 7]
Any help is appreciated!
If you do not care about destroying the original items object you can use these changes
but it relies on several premises like that the overlapping intervals are adjacent.
The main problem in your code is that you do not update the bounds of the currBegin currEnd interval when adding to it.
Other problem is the detection of overlapping intervals.
And the last problem is not remembering which items were already put to some out array (this is solved here by simply deleting the items, which may not be ideal, but can be done otherwise if needed).