Home > Back-end >  Two Number Is in between range in array jquery
Two Number Is in between range in array jquery

Time:08-04

I have two array and need to check any duplicate range in this how can achieve that

let arrayfrom = ['1', '6.1', '10', '31','6.2',3];
let arrayto   = ['2', '9.9', '30', '401','7',5];

How we can test duplicate range? Here the expected result:

1-2   -valid 
6.1 - 9.9 -valid
10 - 30-valid
31 - 401 -valid
6.2 - 7 -invalid (between range 6.1 - 9.9)
3-5 - valid 

Help me to find this solution

CodePudding user response:

A loop or two will do. We need to compare all pairs to all others.

let arrayFrom = ['1', '6.1', '10', '31', '6.2', 3];
let arrayTo = ['2', '9.9', '30', '401', '7', 5];

function is_pair_included(a, in_b) {
  return (a[0] > in_b[0] && a[1] < in_b[1])
}
var to_remove = [];
for (var i = 0; i < arrayFrom.length - 1; i  ) {
  for (var j = i   1; j < arrayFrom.length; j  ) {
    var pair1 = [ arrayFrom[i],  arrayTo[i]];
    var pair2 = [ arrayFrom[j],  arrayTo[j]];

    if (is_pair_included(pair1, pair2)) {
      to_remove.push(i);
    }
    if (is_pair_included(pair2, pair1)) {
      to_remove.push(j);
    }
  }

}


to_remove.forEach(function(i) {
  var pair1 = [ arrayFrom[i],  arrayTo[i]];
  console.log(""   pair1, "invalid");

})

  • Related