我有一个范围值为[1,35]
的数组。然后在第二个数组中我有其他范围,例如 [2,5]、[8,9]
等。
现在我需要从第一个范围中减去这些范围,并得到如下值
[1-1]
(因为取出了2-5
),然后是[6,7]
,然后是[10, 35]
。
所以基本上我想从第二个数组中获取范围并从第一个数组中删除它们。
我该怎么做?
最佳答案
您可以使用下面的 ES6 函数。
它允许您在第一个参数中指定多个范围,并假设它没有重叠的范围。函数的返回值是一个基于第一个参数的数组,但删除了第二个参数中指定的范围。原始数组在此过程中不会发生变化:
function subtractRanges(a, b) {
// Take deep copy of a and sort it
a = a.map( x => [...x] ).sort( (x, y) => x[0] - y[0] );
// Take shallow copy of b and sort it
b = [...b].sort( (x, y) => x[0] - y[0] );
var c = [], i = 0, j = 0;
while (i < a.length && j < b.length) {
var x = a[i], y = b[j];
if (y[0] > x[0]) {
c.push([x[0], Math.min(y[0]-1, x[1])]);
if (y[1] < x[1]) {
x[0] = y[1]+1;
j++;
} else {
i++;
}
} else {
if (y[1] >= x[1]) {
i++;
} else {
if (y[1] >= x[0]) {
x[0] = y[1]+1;
}
j++;
}
}
}
// Add remainder of a, and return
return [...c, ...a.slice(i)];
}
// Sample input
var a = [ [1,35] ];
var b = [ [2,5], [8,9] ];
// Get result
var result = subtractRanges(a, b)
// Output result
console.log(JSON.stringify(result));
关于javascript - 从给定范围中排除多个范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41408690/