My array contains the following data:
[
{ "begin": 870, "end": 889, "spanType": ["plan", "gt-plan"] },
{ "begin": 890, "end": 925, "spanType": ["plan", "gt-plan"] },
{ "begin": 926, "end": 938, "spanType": ["plan", "gt-plan"] },
{ "begin": 939, "end": 958, "spanType": ["plan", "gt-plan"] },
{ "begin": 7732, "end": 7790, "spanType": ["plan", "gt-plan"] },
{ "begin": 7791, "end": 7879, "spanType": ["plan", "gt-plan"] }
]
I am trying to iterate over this array and create a new array with the following structure:
[
{ "begin": 870, "end": 958, "spanType": ["plan", "gt-plan"] },
{ "begin": 7732, "end": 7879, "spanType": ["plan", "gt-plan"] }
]
The goal is to merge two spans together if the end of one span is within 3 units of the beginning of the next span.
This is my current approach (not functioning as intended) - check it out on this demo link:
spans.forEach(function(d,i) {
if (i+1 <= spans.length - 1) {
if (spans[i+1].begin <= d.end + 3) {
d.end = spans[i+1].end;
newSpans.push(d);
}
else {
newSpans.push(spans[i]);
}
}
});
Link to the demo for reference - see fiddle