Click here to Skip to main content
15,912,072 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have validRange(x,y,z) function, it gets an array and 2 numbers, If array's numbers located in this 2 number's range then it returns true, If the array contains a number that is not in the range, the function returns false. For example` validRange([11,1,15,13,14], 10, 20); this will return false, cause 1 is not in range,
validRange([11,15,13,14], 10, 20) and this will return true.

What I have tried:

I have tried like this, but why is it not working?

function validRange(x, y, z) {
	for(var i = 0; i < x.length; i++){
		if(x[i] > y && x[i] < z){
			return true;
		}
		else{
			return false;
		}
	}
}


console.log(validRange([11,1,15,13,14], 10, 20)); //in this case it returns true, but it must return false
Posted
Updated 18-Jul-18 3:23am

1 solution

Your code checks only the first array value and returns immediately. Return immediately only if the condition is not met and return true finally outside the loop:
javascrip
function validRange(x, y, z) {
    for(var i = 0; i < x.length; i++){
        if(x[i] < y || x[i] > z){
            // Value is outside the range
            return false;
        }
    }
    // All values are inside the range
    return true;
}
Note also that I have changed the condition to be outside the range in a way that values which are identical to one of the limits are treated as valid (it is common with ranges that the limits are included). If this should not be the case, change the to comparisons to <= and >=.
 
Share this answer
 
Comments
Suren97 18-Jul-18 9:33am    
Thank you very much

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900