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;
CodePudding user response:
.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);
CodePudding user response:
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
CodePudding user response:
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');
}