0

I am currently writing something that requires checking if one range contains any items from another range

var lvlRange = [];

        for (var i = sLVL; i <= dLVL; i++) {
            lvlRange.push(i);
        } 

var methodRange = [];

        for (var i = skillIdentity.method1Start; i <= skillIdentity.method1End; i++) {
            methodRange.push(i);
        }

For example, if the lvlRange array has everything from 1-30, I need to check if the methodRange also has anything between 1 and 30 in it. Essentially checking if they have any overlapping numbers.

Something like (if lvlRange shares any numbers with methodRange) return true;

bubly
  • 1
  • 2

4 Answers4

0

.filter() returns only true results of a callback. This callback uses .includes() which will compare each number of A to the numbers of B.

const A = [0,11,55,66,77,99,111];
const B = [44,55,88,111,333];

const matches = A.filter(n => B.includes(n));

console.log(matches);
zer00ne
  • 41,936
  • 6
  • 41
  • 68
0

You could check if there is any intersection in the 2 arrays:

function isIntersection(arr1, arr2) {
  const intersection = arr1.filter(x => arr2.includes(x))
  return (intersection.length > 0)
}

var lvlRange = [1, 2, 3, 4, 5, 6, 7];
var methodRange = [0, 4, 8, 9];

// This logs true because the item '4' is present in both arrays
console.log( isIntersection(lvlRange, methodRange) )

This is explained in depth here: https://stackoverflow.com/a/33034768/5334486

GrafiCode
  • 3,307
  • 3
  • 26
  • 31
0

Assuming integers and that the range starts at sLVL and ends at dLVL, the test can be peformed with the some method as follows:

if (methodRange.some(n => n >= sLVL && n <= dLVL)) {
  console.log('methodRange does contain some values in the lvlrange');
}
MikeM
  • 13,156
  • 2
  • 34
  • 47
0

What I understood is that you have two arrays filled with integers. You want to check if in the other array is there any integer from the first array or not. If Yes, you can try this solution :

const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const arr2 = [10, 20, 30, 40, 50];

const matchedResult = arr1.filter(n => arr2.includes(n));

const ifMatched = arr1.some(n => arr2.includes(n));

console.log(matchedResult); // [10]
console.log(ifMatched); // true
Debug Diva
  • 26,058
  • 13
  • 70
  • 123