Home > OS >  How to check duplicate number range element in JavaScript array?
How to check duplicate number range element in JavaScript array?

Time:03-03

For example,

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

In the above example, the third element of the array is duplicate because numberStart and numberEnd ranges already exist in the 2nd element of the array. How to find the duplicate element?

CodePudding user response:

Assume you start with an empty list and you keep adding objects range to it.

One possible solution is the following. The new objects will be added only if they do not overlap the max range of the existing elements.

In the example below only the objects 1, 2, and 5 will be added to the array.

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);

  • Related