If clause with multiple conditions - javascript

I seem to be lost or just seem to be confused.
To simplify the problem: I want to check whether each in an array holds true and if and only if all are true it should return a specific value.
var trueArray=[true,true,true,true];
As in my code, the array can have length up to 100 elements, I can't simply check for every element but need a for loop.
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===true)
{
//do something
}
}
However, the above code does something on each step of the loop but I only want it to do something once every condition held true and not in between. Can't think of the solution at the moment?

Use Array.prototype.every
if (trueArray.every(function(x) { return x; })) {
//do something
}

If it's guaranteed to be a boolean you can check if any of them are false instead of if they're all true with Array.prototype.indexOf
if(trueArray.indexOf(false) === -1) {
// none are false, so do stuff
}
You wouldn't need to use a loop or create a function.

Declare a check variable who is already true and set it to false if one of your array values is false. After that, check if it's true and do something.
Example:
var trueArray=[true,true,true,true];
var bCheckArrayVal = true;
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===false){
bCheckArrayVal = false;
}
if (bCheckArrayVal) {
// do something if true
} else {
// do something if false
}
}

Try the following code:
var currentValue = true;
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===false){
currentValue = false;
}
}
if(currentValue === true){
//do something
}

You should short circuit the logic as soon as you get a false value, must answers are not getting your question because of the misleading logic you put inside the for even though you only want it done once if all values are true.
You need something like
var flag=true;
for(var i =0;i
if (flag) { do something}

You can do it like this...
var trueArray=[true, true, true, true];
var allTrue=false;
for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===false){
allTrue=false;
break;
}
else
{
allTrue=true;
}
}
if(allTrue==true)
{
// do something if all values are true
}
You must break the loop if the false value is detected.

Related

How to loop through a JS set and break when a value is found?

I have 2 sets of URLs. I want to loop through one set and compare each value with .has to the 2nd set.
To that effect I have:
urlSet1.forEach(function(value) {
if (urlSet2.has(value) == false) {
newUrl = value;
return false;
}
})
However, of course, this keeps continuing to loop through.
I tried using every but I get the error:
urlSet1.every is not a function
And of course break; does not work on this either.
Would anyone know how to achieve this?
You should use a for loop.
for( const url of urlSet1 ) {
if( !urlSet2.has(url) ) {
newUrl = url;
break;
}
}
If your goal is to continue running the loop until the condition is met, then you can nest your conditional logic inside a while loop and use a boolean flag to stop the loop from running.
Optionally, you could also use a break; now that a while loop is being used but a boolean flag works just as well without needing to rearrange your logic.
See notes within the snippet below:
var urlSet1 = new Map()
urlSet1.set('abc.com', 'def.com', 'ghi.net', 'jkl.com')
var urlSet2 = new Map()
urlSet2.set('abc.com', 'def.net', 'ghi.com', 'jkl.com')
var newUrl = ''
//set a boolean flag to use as condition for while loop
var running = true
//while running is true, continue running loop
while (running) {
urlSet1.forEach(function(value) {
if (urlSet2.has(value) == false) {
newUrl = value;
console.log(newUrl)
//once condition is met, set boolean flag to false to stop loop
running = false;
console.log(running)
} else {
//some other condition
}
})
}

Difference between JQuery $.each loop and JS for loop [duplicate]

I want to return false and return from function if I find first blank textbox
function validate(){
$('input[type=text]').each(function(){
if($(this).val() == "")
return false;
});
}
and above code is not working for me :(
can anybody help?
You are jumping out, but from the inner loop, I would instead use a selector for your specific "no value" check, like this:
function validate(){
if($('input[type=text][value=""]').length) return false;
}
Or, set the result as you go inside the loop, and return that result from the outer loop:
function validate() {
var valid = true;
$('input[type=text]').each(function(){
if($(this).val() == "") //or a more complex check here
return valid = false;
});
return valid;
}
You can do it like this:
function validate(){
var rv = true;
$('input[type=text]').each(function(){
if($(this).val() == "") {
rv = false; // Set flag
return false; // Stop iterating
}
});
return rv;
}
That assumes you want to return true if you don't find it.
You may find that this is one of those sitautions where you don't want to use each at all:
function validate(){
var inputs = $('input[type=text]');
var index;
while (index = inputs.length - 1; index >= 0; --index) {
if (inputs[index].value == "") { // Or $(inputs[index]).val() == "" if you prefer
return false;
}
}
// (Presumably return something here, though you weren't in your example)
}
I want to add something to existing answers to clear the behavior of $(selector).each and why it doesn't respect return false in OP's code.
return keyword inside $(selector).each is used to break or continue the loop. If you use return false, it is equivalent to a break statement inside a for/while loop. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. Source
Because you're returning false, the loop breaks and the function ends up returning undefined in your case.
Your option is to use a var outside $.each or avoid using it altogether as #TJCrowder wrote.

hasOwnProperty() is only checking if a certain property exists in a JSON, but doesn't return anything if it doesn't

I keep trying different methods to check if this JSON contains "attributes." In this way I can determine if the given coordinates are outside of wetlands. If they are in wetlands, "attributes" will exist in the JSON. If they aren't in wetlands, 'attributes' won't be in the JSON.
When I run this function, I am only getting TRUE - when I type in coordinates that are in a wetland (try 43.088 instead, in the JSON url, which returns true).
However I want FALSE for the given url. For some reason when I do console.log("FALSE"), this doesn't appear or return in the console at all if hasOwnProperty('attributes') == false.
Am I missing something?
function(GetData) {
fetch('https://www.fws.gov/wetlandsmapservice/rest/services/Wetlands/MapServer/0/query?where=&text=&objectIds=&time=&geometry=-88.305%2C43.060&geometryType=esriGeometryPoint&inSR=4326&spatialRel=esriSpatialRelWithin&relationParam=&outFields=WETLAND_TYPE&returnGeometry=false&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&resultOffset=&resultRecordCount=&queryByDistance=&returnExtentsOnly=false&datumTransformation=&parameterValues=&rangeValues=&f=pjson&__ncforminfo=qCOZOO8Kyr4uogGcKvxkzzuK7gmavd4CxwTAkdbAsF2_aT4eeNbB0NpLwCYwiAJSf1ZHqY3CKVZ3osgMevhYGQrqRUQZej5oHaSmnSIaiZZb469Cexv-zqqmgYMuFJAAzrcRxvKXPBz9VnYPnMrM6kBNhO-cz6yK_w5T1mqNu_VXSbjBSihVf4_mlUBSVb9yf4C8scYXWm9Iak2Nfn1dtJACNUHLBHSElLvc1wxFMO2eUWNsD3qpCk3kAcRyYftuFU86n7THyk2IvkIUpxNmDHRxmmbgSYvPLMkl8t41Jzjp_bntkIyOWB0u8cQU2VsfASFUdznRkvrvYrQxgR8eyvsPq5oV_ZoPSksVCew6xev0K_TV2NU-kjojYpowMVXpZtCX9P-Q_7m8ywt2PyLPhEVgQB12ji1S7G5FRzIt6E0SDoXMY1vqQvPtedaNYbBCazXgs05L9DFKdtvrwmQVCeLmpBTduIhF9Sk4kozMnFX6GOANrZJMCI9AssN0DjrhlZkgDVw0l1flF44Zli927CXGTQ-oUpwsn7PPypVkN2iDJf-nz9XNbj82sv1c6B5s5UZVwiOp8VHJfZSDJ8BAYR4z_oONT2JwbVSKKlFKeN72f-Y6EejcB9wPKmn5kYjv7CKkRyIIv4F4cqVWxLK9x33uvEDMTvxX')
.then(function(response) {
return response.json();
})
.then(function(data) {
appendData3(data);
})
.catch(function(err) {
console.log('error: ' + err);
});
function appendData3(data) {
for (let obj of data['features']) {
if (obj.hasOwnProperty('attributes') == false) {
console.log("FALSE");
} else {
console.log("TRUE");
}
}
}
};
The issue is that in the response data['features'] is empty. When iterating over an empty array, nothing within the for...of loop is executed.
const emptyArray = [];
for (const item of emptyArray) {
// body is never executed...
}
If just checking the presence of an item within data['features'] is enough, you could use the length of the array.
function appendData3(data) {
if (data.features.length > 0) {
console.log("TRUE");
} else {
console.log("FALSE");
}
}
To check if one of the elements has the property "attributes" you could use some():
function appendData3(data) {
if (data.features.some(item => item.hasOwnProperty("attributes"))) {
console.log("TRUE");
} else {
console.log("FALSE");
}
}
If you're just trying to find out if a specific point is within one of the wetlands polygons, you could let the server to do the hard job and simplify your request. For example, ask for count.
See returnCountOnly at https://developers.arcgis.com/rest/services-reference/enterprise/query-feature-service-layer-.htm
https://www.fws.gov/wetlandsmapservice/rest/services/Wetlands/MapServer/0/query?geometry=-88.305%2C43.060&geometryType=esriGeometryPoint&inSR=4326&spatialRel=esriSpatialRelWithin&returnCountOnly=true&f=pjson
https://www.fws.gov/wetlandsmapservice/rest/services/Wetlands/MapServer/0/query?geometry=-88.305%2C43.088&geometryType=esriGeometryPoint&inSR=4326&spatialRel=esriSpatialRelWithin&returnCountOnly=true&f=pjson
I tested your code and this is the problem. When the coordinates are outside the wetlands, the features array is empty, that means nothing happen in your for loop. So do this instead of checking directly inside of your for loop
function appendData3(data) {
// Here we check if features is empty by checking it's length
if (data['features'].length == 0) {
console.log("FALSE")
}
for (let obj of data['features']) {
console.log("TRUE");
}
}
I also see that your for loop is only getting one object every time so instea of doing a for loop, just do it like this:
function appendData3(data) {
var obj = data['features'][0]
if(obj) {
console.log('TRUE')
} else {
console.log('FALSE')
}
}
As you can see, I did it even easier this time, just by getting the first object of features and checking if it exist.
Also, small tip: when you want to check if a condition is false, don't use == false, just put an exclamation mark at the beginning of the if statement. Like that:
if(!obj.hasOwnProperty('attributes')) { 
// Code here will be executed if the condition is false
} else {
// Code here will be executed if the condition is true
}
I hope this help you fixing your problem.
Have a nice day :)

.validate rule: check jquery var

So, i'm trying to take a jQuery var and use it as a rule for the .validate plugin.
The var comes from a function that runs a function and give 1 for true and 0 for false, the problem is that i can't make the rule return true or false for the validate function. The code reads:
$.validator.addMethod("cpfc", function(){
if (($(CPF.valida($(cpf).val())).size()) === '1' )
{
return true;
}
else
{
return false;
}
});
$(CPF.valida($(cpf).val())).size() = 1 or 0, depends on the function check, I ran this function on the console and it's returning the correct values.
Any help will be appreciated
You have a semi-colon between the if and else statement which will be causing a syntax error. Also note that size() (aside from being deprecated) returns an integer, so your current code will always return false as you compare it to a string. It's now recommended to use the length property instead:
$.validator.addMethod("cpfc", function(){
if ($(CPF.valida($(cpf).val())).length === 1) {
return true
} else {
return false
}
});
This can be further reduced to just
$.validator.addMethod("cpfc", function(){
return $(CPF.valida($(cpf).val())).length === 1;
});
You should also ensure that the CPF object and cpf variable are in scope and hold the values you expect when called from within the validator method.

Angularjs filter always returns true

I've made filter for ng-repaet that looks like this:
$scope.filterRoutine = function(col) {
return _.isEqual(col.Routine.IsIndoor, true);
}
It works fine (isEqual returns true or false).
But this doesn't work, and I don't know why is that (when I say it doesn't work, I don't get any errors, but view doesn't change)
$scope.filterRoutine = function(col) {
return _.forEach(tempData, function (temp) {
if (_.find(col.Exercises, { Exercise: temp })) {
return true;
} else {
return false;
}
});
}
What I do here (or rather what I want to do) is this: I have tempData collection, if my col.Exercises has at least one item from tempData it should be showed in the view.
But for some reason all items are showed in the view i.e. nothing has been filtered.
My guess is that this because this function always returns true (because always at least one col.Exercises should contain item from tempData).
How can I fix this i.e. hide all cols which don't contain any items from tempData ?
Returning from _.forEach does not do what you expect it to do.
You'll need to do something like this:
$scope.filterRoutine = function(col) {
var x = false;
_.forEach(tempData, function (temp) {
if (_.find(col.Exercises, { Exercise: temp })) {
x = true;
}
});
return x
}
Also, "Callbacks may exit iteration early by explicitly returning false.", meaning your return false was stoping iteration after the first time _.find returned false.

Categories

Resources