js if any value in array is under or over value

こ雲淡風輕ζ 提交于 2020-07-18 10:23:21

问题


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.


回答1:


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.




回答2:


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;
});



回答3:


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


来源:https://stackoverflow.com/questions/37373225/js-if-any-value-in-array-is-under-or-over-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!