如何检查JavaScript数组中重复的数字范围元素



例如,

[{
"numberStart": "300",
"numberEnd": "350",
"id": "1"
}, {
"numberStart": "351",
"numberEnd": "400",
"id": "2"
}, {
"numberStart": "380", 
"numberEnd": "400",
"id": "3"
}]

在上例中,数组的第三个元素是重复的,因为数组的第二个元素中已经存在numberStart和numberEnd范围。如何查找重复元素?

假设您从一个空列表开始,并不断向其中添加对象范围。

一种可能的解决方案如下。只有当新对象不与现有元素的最大范围重叠时,才会添加新对象。

在下面的示例中,只有对象1、2和5将被添加到阵列中。

let list = [];   // start with an empty list
//--------------------------------
function addToList(list , toAdd) {
const maxValue = Math.max(...list.map(o => o.numberEnd), 0);
if (toAdd.numberEnd > maxValue) list=[{...list,...toAdd}];
return list;
}
//--------------------------------
list = addToList(list,{"numberStart": 300,"numberEnd": 350, "id": "1"});  // will be added
list = addToList(list,{"numberStart": 351,"numberEnd": 400, "id": "2"});  // will be added
list = addToList(list,{"numberStart": 380, "numberEnd": 400, "id": "3"}); // it will not be added
list = addToList(list,{"numberStart": 200, "numberEnd": 300, "id": "4"}); // it will not be added
list = addToList(list,{"numberStart": 401, "numberEnd": 500, "id": "5"}); // will be added
console.log(list);

最新更新