CLWONG CLWONG - 1 month ago 6
Javascript Question

Check if an integer is within one of the ranges

Don't down vote me yet. It is not an duplicated question.

I have an 2D array, which contains three ranges:

ranges = [
[1,4],
[6,10],
[15,20]
]


I want to check if a number is within one of the ranges.

For example,
7
is true as it is within
[6,10]


I tried to write in this way:

if ( (num >= ranges[0][0] && num =< ranges[0][1]) ||
(num >= ranges[1][0] && num =< ranges[1][1]) ||
(num >= ranges[2][0] && num =< ranges[2][1])) {
return True;
}
else {
return false;
}


I got two questions:

(1) Is there any faster method instead of writing this clumsy code?

(2) If the size of ranges array is unknown(not fixed), how can I check the number?

Answer

You could use Array#some and check the interval.

The some() method tests whether some element in the array passes the test implemented by the provided function.

function checkAgainst(value) {
    return ranges.some(function (a) {
        return value >= a[0] && value <= a[1];
    });
}

var ranges = [[1, 4], [6, 10], [15, 20]];
  
console.log(checkAgainst(3));
console.log(checkAgainst(5));
console.log(checkAgainst(300));

Comments