Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js if any value in array is under or over value

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.

like image 839
Alex-c Avatar asked May 22 '16 10:05

Alex-c


1 Answers

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.

like image 176
Pavlin Avatar answered Nov 13 '22 11:11

Pavlin