Nested IF-FOR-IF loops - javascript

I'm stuck in nested loops.
this.isRyt is a variable where a retrived string from JSON is stored.
i is a user input variable of type string.
this.storeArray[] is an array where every input of i from user will be stored only if it matches the string stored in this.isRyt variable.So basically I want to compare the strings stored in this.storeArray[] by using index k to the string stored in this.isRryt(as multiple i inputs from user will stored at different index locations in this.storeArray[]),and if the string is not matched then there is variable counter which will get incremented.incCounter is nothing but a simple counter variable initialized with value 0.
My try: I tried using the below loop , but this.counter++ get incremented multiple times in a single time(multiple iterations of k) as it is inside the for loop. I want to make it increment only a single time but the for condition should not be omitted.
filterAnswer(i:any) //Comparing Answer submitted by user with JSON answer
{
this.isRyt = this.questArrayNew1[0].isRight;
if(this.isRyt == i )
{
for(let k = 0 ; k < this.questArray.length ; k++)
{
if(this.storeArray[k] == i)
{
console.log(k);
}
else
{
this.counter++; //WANT TO INCREMENT ONLY ONE TIME IF IT DOESNT SATISFY THE CONDITION FOR WHOLE K=0,1,2,3.. variable
}
}
this.storeArray[this.incCounter] = i ;
console.log(this.storeArray);
this.incCounter++;
}
else
{
return 0;
}
}

If I am understanding you correctly, this.counter only needs to be incremented once. You could try something like this:
filterAnswer(i:any) //Comparing Answer submitted by user with JSON answer
{
var notCounted = true; //condition for this.counter++ code block to be executed
this.isRyt = this.questArrayNew1[0].isRight;
if(this.isRyt == i )
{
for(let k = 0 ; k < this.questArray.length ; k++)
{
if(this.storeArray[k] == i)
{
console.log(k);
}
else
{
while(notCounted)
{ //executes while bool is true
this.counter++;
notCounted = false; //incremented so now no longer needed
}
}
}
this.storeArray[this.incCounter] = i ;
console.log(this.storeArray);
this.incCounter++;
}
else
{
return 0;
}
}

Related

Comparing JSON string element with JavaScript string

I have came across an odd problem with getting JSON data like the following.
[
{
"type":"ripe",
"red":137,
"green":68,
"blue":40,
"strftime(\"%H:%M:%S\", time)":"18:46:37"
},
]
I was not able to compare this data by type using JavaScript, they both successfully went through my if statement for some odd reason. The total count for both variables is equal to 2.
let counterLoop = function() {
for (let i = 0; i < data.length; i++) {
let fruitType = JSON.stringify(data[i].type);
sortFruit(fruitType.toLowerCase());
}
}
let sortFruit = function(fruitType) {
if (fruitType.localeCompare('ripe') === 0){} {
totalRipeFruit++;
$("#totalRipeFruit").text(totalRipeFruit);
}
if (fruitType.localeCompare('unripe') === 0){} {
totalUnripeFruit++;
$("#totalUnripeFruit").text(totalUnripeFruit);
}
}
Any idea why this could be the case?
Thank you very much!
You have two problems here; First of all there is no need for the JSON.stringifyon the type, just leave it out as it will return the string containing useless quotes.
Secondly, your if statements are messed up: You have a second pair of brackets behind each one, so simply change
if (fruitType.localeCompare('ripe') === 0){} {
totalRipeFruit++;
$("#totalRipeFruit").text(totalRipeFruit);
}
if (fruitType.localeCompare('raw') === 0){} {
totalRawFruit++;
$("#totalRawFruit").text(totalRawFruit);
}
To:
if (fruitType.localeCompare('ripe') === 0) {
totalRipeFruit++;
}
if (fruitType.localeCompare('raw') === 0) {
totalRawFruit++;
}

Loop for when i exclude one element

i have this variable:
qtdPerguntasGerarQuiz = 2
and i have this array:
idQuestoesUnidadeLivro = [3,4,50]
for (let k = 0; k < qtdPerguntasGerarQuiz; k++) {
pergunta = await this.getPerguntaAleatoria(idQuestoesUnidadeLivro) // here i get one object
if (pergunta.rows[0].type_answer === 'Multipla Escolha') { // is entering in this if
optionCorreta = await this.getOptionCorreta(pergunta.rows[0].id)
if(!optionCorreta.rows[0]){ //also entering here
for(let i_find = 0; i_find < idQuestoesUnidadeLivro.length; i_find++){
if(idQuestoesUnidadeLivro[i_find] === pergunta.rows[0].id){ //is entering here and excluding the idQuestoesUnidadeLivro[i_find] that is equal to pergunta.rows[0].id
idQuestoesUnidadeLivro.splice(i_find,1)
qtdPerguntasGerarQuiz--;
break; //don't continue the for of i_find
}
}
return
}
// Continue the process if don't enter in the condition if(!optionCorreta.rows[0])
optionsPergunta.push(optionCorreta.rows[0])
...
When i'm excluding one item of my array idQuestoesUnidadeLivro.splice(i_find,1)) i need to stop the for (because i find the element that i need to exclude), if the condition is true, this element don't have appear again in the first for(), so i splice() and i decrement 1 to avoid loop.
If the element is excluded, i need to return to the start of the first for().
My problem is when my condition enter in the if(idQuestoesUnidadeLivro[i_find] === pergunta.rows[0].id) the for entering in eternal loop and i can't find why.
Try to remove return command after if.
It could finish your function by return.
And update break to the below.
OUTER_LOOP: for (let k = 0; k < qtdPerguntasGerarQuiz; k++) {
...
qtdPerguntasGerarQuiz--;
break OUTER_LOOP; //don't continue the for of i_find
In your code, when the condition !optionCorreta.rows[0] meets, then the function ends, no matter what any other condition check or the splice action happens.
So let's try to refactor your code by removing the return statement:
for( ) {
if( !optionCorreta.rows[0] ) {
....
for( ) {
if( ) {
splice()
break;
}
} else {
optionsPergunta.push(optionCorreta.rows[0]);
}
}
In this way when the break statement reaches, it exits the inner loop. Now since the other lines are inside the else, then it gets back to start of the first loop.
In the case of infinite loop, did you step through your code in the node debugger? There may be problems with getPerguntaAleatoria(idQuestoesUnidadeLivro) or getOptionCorreta(pergunta.rows[0].id) methods.
try using a flag for control push line
idQuestoesUnidadeLivro = [3,4,50]
let mustPushOptionCorreta = true;//***
let addedPerguntasGerarQuiz = 0;
for (let k = idQuestoesUnidadeLivro.length - 1; k >= 0 && addedPerguntasGerarQuiz < qtdPerguntasGerarQuiz; k--) {
pergunta = await this.getPerguntaAleatoria(idQuestoesUnidadeLivro) // here i get one object
if (pergunta.rows[0].type_answer === 'Multipla Escolha') { // is entering in this if
mustPushOptionCorreta = true;//***
optionCorreta = await this.getOptionCorreta(pergunta.rows[0].id)
if(!optionCorreta.rows[0]){ //also entering here
for(let i_find = 0; i_find < idQuestoesUnidadeLivro.length; i_find++){
if(idQuestoesUnidadeLivro[i_find] === pergunta.rows[0].id){ //is entering here and excluding the idQuestoesUnidadeLivro[i_find] that is equal to pergunta.rows[0].id
idQuestoesUnidadeLivro.splice(i_find,1)
qtdPerguntasGerarQuiz--;//I guess you should remove this line
mustPushOptionCorreta = false
break; //don't continue the for of i_find
}
}
}
// Continue the process if don't enter in the condition if(!optionCorreta.rows[0])
if(mustPushOptionCorreta) {//***
optionsPergunta.push(optionCorreta.rows[0])
addedPerguntasGerarQuiz++
If I guess right, you want create a quiz with qtdPerguntasGerarQuiz questions in it. Why when you select an inappropriate question, reduce qtdPerguntasGerarQuiz?

need help understanding using an associative array to keep track of array value appearances

code:
method = function(a) {
//use associative array to keep track of the total number of appearances of a value
//in the array
var counts = [];
for(var i = 0; i <= a.length; i++) {
if(counts[a[i]] === undefined) {
//if the condition is looking for a[0],a[1],a[2],a[3],a[4],a[5] inside counts[] one value at a time and does not find them inside counts[] it will set each value to 1
counts[a[i]] = 1;
console.log(counts[a[i]]);
} else {
return true;
}
}
return false;
}
the js console logs 1x6
how can the condition see if a value inside counts[a[i]] has been repeated if all of the counts[a[i]] values are being set to 1 each iteration? wouldn't it always be comparing 1 to 1?
for example, if the a array is [1,2,3,4,5,2] and counts[a[1]](first int 2 in the array) is undefined and then set to 1, how would the condition know that counts[a[5]](second int 2 in the array) is the same value as counts[a[1]] and therefore it should return true?
perhaps I am misunderstanding whats going on.
I would appreciate any help. thanks
function counter(){
this.counts=[];
}
counter.prototype.add=function(a){
if(this.counts[a] === undefined) {
this.counts[a] = 1;
console.log(this.counts);
} else {
return true;
}
return false;
}
try this:
c= new counter();
c.counts;//[]
c.add(1);
c.counts;//[ ,1]
c.add(5);
c.counts;//[ ,1, , , ,1]
c.add(1);//true
...
may it helps you to understand whats going on

How i can get value $scope.TobaccoProduct_0 , $scope.TobaccoProduct_1

How i can get value of TobaccoProduct_0 , TobaccoProduct_1, TobaccoProduct_2.
Currently i am trying with this code and its not working
for (var count = 0; count < $scope.ProductCount; count++) {
if ($scope.TobaccoProduct_[count] == true) {
$("#SmokeReview").submit();
} else {
alert("plz chcek atleast one value");
}
}
for (var count = 0 ; count < $scope.ProductCount; count++) {
if ($scope["TobaccoProduct_"+count] == true) {
$("#SmokeReview").submit();
}
else {
alert("plz chcek atleast one value");
}
}
You really shouldn't be doing it this way though. You should surely be using some kind of array to store the Tobacco products rather than numbering the variable name.
Edit: You might actually be doing it that way (otherwise you'd have a really strange ProductCount implementation) and so the above solution won't work, you'll have to use $scope.TobaccoProduct[count]

Javascript : How can I add X elements to an array

I need to create an array including the first 100 prime numbers, here is my code:
var premier= [];
var nombre= premier.length;
function isPrime(n)
{
if(n < 2)
{
return false;
}
for(i=2; i<Math.sqrt(n); i++)
{
if(n%i===0)
{
return false;
}
}
return true
};
while(nombre<100)
{
var j=2
if(isPrime(j)==true)
{
premier.push(j);
}
j=j+1
}
I am a beginner in Javascript, but I have tested the isPrime function and it works fine even forlarge numbers.
but when I run the program I have:
FATAL ERROR: JS Allocation failed - process out of memory
I think this part is wrong:
while(nombre<100)
{
var j=2
if(isPrime(j)=true)
{
premier.push(j);
}
j=j+1
}
console.log(premier)
But I can't tell why
You are repeatedly setting j=2 every time the loop runs, and you never change nombre so the loop will never end. Note that JavaScript sets literal vaues by value, not by reference, so nombre = premier.length won't magically update.
Additionally, statements of the form if( x = true) will set x to true, and then pass the condition automatically. In this case, since x is a function call, it is invalid syntax.
Did you mean this?
var j = 2;
while(premier.length < 100) {
if( isPrime(j)) premier.push(j);
j++;
}

Categories