VICTOR
VICTOR

Reputation: 1942

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?

Upvotes: 1

Views: 364

Answers (4)

Christos
Christos

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

Niyoko
Niyoko

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

Emil S. J&#248;rgensen
Emil S. J&#248;rgensen

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

Nina Scholz
Nina Scholz

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

Related Questions