js if any value in array is under or over value

2020-08-25 05:49发布

say you have (any amount) values in an array and you want to see if any of them is over (lower amount) and under higher amount, how would you do that?

answer without doing a for loop or any lengthy code.

Maybe something like:

var havingParty = false;
if ((theArrayWithValuesIn > 10) && (theArrayWithValuesIn < 100)) {
    havingParty = true;
} else {
    havingParty = false;
}

would work.

Please note: x and y, collision detection, compact code.

3条回答
神经病院院长
2楼-- · 2020-08-25 06:13

If I understand your question correctly, you want to check if a given array has any value greater than some other value.

There is a useful function for this called some (Documentation here)

An example of using this would be:

const a = [1, 2, 3, 4, 5];
a.some(el => el > 5) // false, since no element is greater than 5
a.some(el => el > 4) // true, since 5 is greater than 4
a.some(el => el > 3) // true, since 4 and 5 are greater than 3

A similar function to this is every, which checks if all the values fulfil a given condition (Documentation here).

An example of this would be:

const a = [1, 2, 3, 4, 5];
a.every(el => el > 3) // false
a.every(el => el > 0) // true

My examples simply check for greater than, but you could pass in any callback that returns a boolean value for more complicated checks.

So for your example, something like this might do the trick if you want to check that all the elements fill the requirement:

const havingParty = theArrayWithValuesIn.every(el => el < 100 && el > 10);

or

const havingParty = theArrayWithValuesIn.some(el => el < 100 && el > 10);

if you you only care that at least one element fills the requirement.

查看更多
啃猪蹄的小仙女
3楼-- · 2020-08-25 06:14

According to your condition

"if any of them is over (lower amount) and under higher amount"

Array.some function will be the most suitable "tool":

var min = 10, max = 100,
    result1 = [1, 2, 3, 30].some((v) => min < v && v < max),
    result2 = [1, 2, 3, 10].some((v) => min < v && v < max);

console.log(result1);  // true
console.log(result2);  // false
查看更多
不美不萌又怎样
4楼-- · 2020-08-25 06:17

Here is a simple answer :

var arr = [0,10,100,30,99];
var config = {min:0,max:100};

// filter is a method that returns only array items that respect a 
//condition(COND1 in this case )
var arr2 = arr.filter(function(item){
  //COND 1 : 
  return item > config.min && item < config.max;
});
查看更多
登录 后发表回答