我需要从主范围分割范围。例如
var start = 0;
var end = 100;
var ranges = [
{ start: 25, end: 50 },
{ start: 60, end: 70 }
]
我的预期输出是,
{ start: 0, end: 24},
{ start: 51, end: 59},
{ start: 71, end: 100}
如何实现这个目标?
答案 0 :(得分:1)
我们可以通过遍历每个范围并将中间范围推送到结果数组来解决这个问题。下面的解决方案允许范围未排序,但是,不允许豁免范围:
要考虑到这些条件,您必须扩展我的代码。如果你不知道怎么做,请告诉我,我会帮忙!
var start = 0;
var end = 100;
var ranges = [
{ start: 0, end: 5 },
{ start: 25, end: 50 },
{ start: 60, end: 70 }
]
// First sort the ranges based on the start
var sortedRanges = ranges.sort(function(a,b) {
return a.start - b.start;
});
var res = [];
// Push each of the intermediate ranges to the result array
for (var i = 0; i < ranges.length; i++) {
if (ranges[i].start == start) {
start = ranges[i].end+1;
continue;
}
res.push({
start: start,
end: ranges[i].start - 1
});
start = ranges[i].end+1;
}
// Push the final range to the resultArray
res.push({start: start, end: end});
console.log(res);
&#13;
答案 1 :(得分:-1)
这是一个简单的代码:
ranges.filter(function(item){return item.start>=start && item.end<=end})