找出数组中存在重叠的对象并仅返回该类对象
过滤存在区间重叠的数组元素
给定如下对象数组:
[ { "id": "line-23746045", "line_top": 543, "line_bottom": 521 }, { "id": "line-23746033", "line_top": 132, "line_bottom": 110 }, { "id": "line-23746031", "line_top": 138, "line_bottom": 116 }, { "id": "line-23746029", "line_top": 143, "line_bottom": 121 } ]
需求是仅保留那些line_top和line_bottom组成的区间与数组中其他元素区间存在重叠的对象。上述数组里,line-23746045的区间(521-543)和其他元素的区间无重叠,因此过滤后期望得到:
[ { "id": "line-23746033", "line_top": 132, "line_bottom": 110 }, { "id": "line-23746031", "line_top": 138, "line_bottom": 116 }, { "id": "line-23746029", "line_top": 143, "line_bottom": 121 } ]
实现思路与代码
要实现这个需求,可按以下步骤操作:
- 先为每个元素确定区间的上下限(确保下限小于上限,用
Math.min和Math.max处理) - 遍历数组,检查每个元素是否存在至少一个其他元素,两者区间存在重叠
- 保留满足重叠条件的元素
以下是JavaScript实现代码:
const lines = [ { "id": "line-23746045", "line_top": 543, "line_bottom": 521 }, { "id": "line-23746033", "line_top": 132, "line_bottom": 110 }, { "id": "line-23746031", "line_top": 138, "line_bottom": 116 }, { "id": "line-23746029", "line_top": 143, "line_bottom": 121 } ]; // 判断两个区间是否重叠的辅助函数 function isOverlap(range1, range2) { return range1.start < range2.end && range2.start < range1.end; } const filteredLines = lines.filter(line => { // 确定当前元素的区间范围 const currentRange = { start: Math.min(line.line_top, line.line_bottom), end: Math.max(line.line_top, line.line_bottom) }; // 检查是否存在其他元素与当前区间重叠 return lines.some(otherLine => { if (otherLine.id === line.id) return false; // 跳过自身 const otherRange = { start: Math.min(otherLine.line_top, otherLine.line_bottom), end: Math.max(otherLine.line_top, otherLine.line_bottom) }; return isOverlap(currentRange, otherRange); }); }); console.log(filteredLines);
运行代码后,输出结果将符合预期。
内容的提问来源于stack exchange,提问作者MrIsoMan
相关产品推荐
相关产品推荐

