Reputation: 1942
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?
Upvotes: 1
Views: 364
Reputation: 53958
You could try something like this:
var isInsideAllRanges = ranges.some(function(range){
return num>=range[0] && num<=range[1];
});
var ranges = [
[1,4],
[6,10],
[15,20]
];
var num = 7;
var isInsideAllRanges = ranges.some(function(range){
return num>=range[0] && num<=range[1];
});
console.log(isInsideAllRanges);
The some
method:
The some() method tests whether some element in the array passes the test implemented by the provided function.
For further info, please have a look at Array.prototype.some()
Upvotes: 1
Reputation: 7672
Another solution is to use map
and reduce
.
var ranges = [
[1,4],
[6,10],
[15,20]
];
function check(number) {
return ranges.map(function(n){
return number >= n[0] && number <= n[1];
}).reduce(function(a, b){
return a || b
}, false);
}
console.log("1: " + check(1));
console.log("5: " + check(5));
console.log("7: " + check(7));
Upvotes: 1
Reputation: 6366
ranges = [
[1, 4],
[6, 10],
[15, 20]
]
function inRange(n) {
for (var i = 0; i < ranges.length; i++) {
if (n >= ranges[i][0] && n <= ranges[i][1]) {
return true;
}
}
return false;
}
console.log(inRange(16),inRange(12),inRange(21))
Upvotes: 0
Reputation: 386604
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));
Upvotes: 6