Why wont my loop within a loop in Javascript work? - javascript

This is suppose to store the chosen answer for multiple questions. When I use this code, it only checks the first question and disregards the other questions.
for(i = 0; i < questions.length-1; i++){
radios = document.getElementsByName(questions[i]);
for (var t = 0; length < radios.length; t++) {
if (radios[t].checked) {
var qResults = JSON.parse(localStorage["qResults"]);
num = radios[t].value;
checked = num.toString();
var temp = (id[0] + ";" + questions[i] + ";" + checked);
alert(temp);
qResults.push(temp);
localStorage["qResults"] = JSON.stringify(qResults);
}
}
alert("question finished");
}

Your inner loop is wrong. Change this:
for (var t = 0; length < radios.length; t++) {
to:
for (var t = 0; t < radios.length; t++) {
Side note: I would suggest that you read the local storage before the loops, and write it back after the loops, instead of doing it for every question.

In addition to Guffa's fix, I think it makes more sense if you can move var qResults and localStorage["qResults"] outside of the second for loop:
var qResults = JSON.parse(localStorage["qResults"]);
for loop I {
for loopII {}
}
localStorage["qResults"] = JSON.stringify(qResults);

Related

Conditional Pop-up Box within a for loop (Sheets)

I got the code below working, but when I try to add a Browser.msgBox() once there is a duplicate in the comparison, the code keeps running until it exceeds its time limit.
The idea is to notify the user that the item he/she is trying to add is duplicated and have the script stop running.
var duplicate = false;
for(var x = 0; x < data.length; x++) {
for(var j = 0; j < dataArquivoItens.length; j++){
if(data[x].join() == dataArquivoItens[j].join()){
duplicate = true;
break;
}
}
}
Thanks a lot!
You are only breaking out from the if statement, this is why your code keeps iterating
If you want to break from all nested loops/ statements - give them a name
Sample:
var duplicate = false;
loop1:
for(var x = 0; x < data.length; x++) {
loop2:
for(var j = 0; j < dataArquivoItens.length; j++){
if(data[x].join() == dataArquivoItens[j].join()){
duplicate = true;
Browser.msgBox("That's a duplicate");
break loop1;
}
}
}

this code is supposed to delete duplicate values and delete empty spaces but it is deleting unique values as well

this code is supposed to delete duplicate values and delete empty spaces but it is deleting unique values as well.
cnt = 0;
for (let i = 0; i < this.fin.length; i++) {
for (let j = 0; j < this.fin.length; j++) {
if (this.fin[i] == this.fin[j]) {
cnt++;
if (cnt > 1) {
this.fin[j] = '';
}
}
if (j == this.fin.length - 1) {
cnt = 0;
}
}
}
this.ntmtg1 = true;
count = 0;
for (let j in this.fin) {
if (this.fin[j] == '') {
this.fin.splice(parseInt(j));
}
}
your logic is almost correct. The couple of mistakes you did are:-
In the for loop in the last part of your code, when you use for( let i in SomeCollection) 'i' will be the value and not index in the array. I think you want to access the index and not the value. I think you should use should use traditional for loop like for(int i =0; i<fin.length;i++).
You need to use splice with two arguments to delete some value from the array.
here is the link https://www.w3schools.com/jsref/jsref_splice.asp
You can do that in simply just one line of code with ES6 feature and Set :
var fin = ["Vivek","Vivek","Mak","Nik","Mak","Hir","Hari","Nur","Nik"];
var result = [...new Set(fin)];
console.log("Fin Total :" , fin.length , ", Result Total :" , result.length);
console.log(result);
Couple of fixes to your code
don't use for in if you're going to mutate the array
splice with only one argument splices from the index to the end of the array, so add a second argument, the length of the splice
in the code below, I omit this for simplicity
Also, I moved were cnt is defined, so no if condition gymnastics needed to reset it
const fin = [1,3,6,7,3,2,4,5,6,4,3,2,1,4,5];
for (let i = 0; i < fin.length; i++) {
let cnt = 0;
for (let j = 0; j < fin.length; j++) {
if (fin[i] == fin[j]) {
cnt++;
if (cnt > 1) {
fin[j] = '';
}
}
}
}
let count = 0;
for (let i = 0; i < fin.length; i++) {
if (fin[i] == '') {
fin.splice(i, 1);
--i; // we've removed an item
}
}
console.log(fin);
fin:any = ["OMAD","SVAC","SVCH","SVAD","LGAG","OMAM","OTBK","OTBH","LGAX","LGBL","SVAN","LGAD","SVAB","SKAP","LGRX","SVAA","SVAS","DNAS","EGEI","NCAT","SVBS","SVBL","SVFM","EPKG","OBBB","OBBS","OBKH","LTFD"
,"SVBC","SVBI","SVBM","SVBB","SVBO","TNCB","SVBZ","SKBU","SKBN","SVCI","SVCD","SVCL","SVCN","SVCC","SVCS","SVCO","SVCZ","SKGO","SVCP","NZCG","SVQM","SVCA","LGSA","MWCB","CYCK","SVCB","SVPI","MRCU","EKCN"
,"SVCR","SKCV","SVUR","SVCU","SVRB","TNCF","TNCC","LGTT","VRMD","OMDW","SVLL","SVED","SVRS","SVEM","SVJI","SVVG","LGEL","SVEZ","NZEV","EDTF","SVFT","VRMR","SKGB","SVGU","SVGD","SVGT","SVGI","SVQJ","EKHM"
,"SVQF","LSPK","SVQL"];

Need to filter out repeating consecutive characters in a string using JavaScript

It is one of the challenges in Codewars, and I am supposed to write a function that will take a string and return an array, in which I can't have two consecutive identical elements. Also, the order should not change.
For example, if I pass a string "hhhhheeeelllloooooohhheeeyyy", then the function should return an array = ["h","e","l","o","h","e","y"].
This is my code.
var uniqueInOrder=function(iterable){
//your code here - remember iterable can be a string or an array
var unique = [];
for( var i = 0; i < iterable.length; i++) {
unique.push(iterable[i]);
}
for( var j = 0, k = 1; j < unique.length; j++, k = j + 1 ){
if(unique[j] === unique[k]){
unique.splice(k,1);
}
}
return unique;
}
so, if I pass a string, such as "hhhhheeeeeellllloooo",it doesn't work as I intend it to because the value of j keeps incrementing, hence I can't filter out all the identical elements.
I tried tweaking the logic, such that whenever the unique[j] === unique[k] the value of j would become zero, and if that's not the case, then things would continue as they are supposed to do.
This got me an infinite loop.
I need your help.
The second for loop is fail because unique.length is not constant during the run.
I think your problem can be solved like this:
var temp = iterable[0];
unique.push(iterable[0]);
for( var i = 1; i < iterable.length; i++) {
if(iterable[i] != temp) {
unique.push(iterable[i]);
temp = iterable[i];
}
}
Hope it helps!
You only need to compare the current index of iterable against the last character in unique:
function(iterable){
var unique = []
for(var i=0; i< iterable.length; i++){
if(unique.length < 1){
unique.push(iterable[i])
} else if(iterable[i] !== unique[unique.length - 1]) {
unique.push(iterable[i])
}
}
return unique
}
I think this will help you:
var word="hhhhheeeelllloooooohhheeeyyy"
function doit(iterable){
var unique = []
unique[0]=iterable[0]
for(var i=1; i< iterable.length; i++){
if(iterable[i] !== unique[unique.length - 1]) {
unique.push(iterable[i])
}
}
return unique
}
alert(doit(word))
for loop will not fail because unique.length is dynamic, i.e will change with addition of new elements to array.
Tested in Internet Explorer too.
Here is the link to jsfiddle: https://jsfiddle.net/kannanore/z5gbee55/
var str = "hhhhheeeelllloooooohhheeeyyy";
var strLen = str.length;
var newStr = "";
for(var i=0; i < strLen; i++ ){
var chr$ = str.charAt(i);
//if(i==0) {newStr = chr$ };
if(chr$ == str.charAt(i+1)){
strLen = str.length;`enter code here`
}else{
newStr = newStr + chr$ ;
}
}
//document.write(newStr);
console.log(newStr);
//Answer: helohey

setting a variable to each element of an array

i have function:
function getFieldNames(arrayOfRecords) {
var theStuff;
for (var i = 0; i = arrayOfRecords.length - 1; i++){
theStuff = arrayOfRecords[i];
theList = theStuff.split('" ');
for (var j = 0; j = theList.length - 1; j++) {
var v = theList[j].split('="');
fName1[i][j] = v[0];
}
}
return fName1;
}
the argument arrayOfRecords is an array, and i dont know how to setup to the 'theStuff' variable an array element? When I do like it is above, i get something stupid.
can anyone help me? :)
There may be other problems but the one that leaps out at me is your for loop header:
for (var i = 0; i = arrayOfRecords.length - 1; i++)
The second part should be a condition, which when evaluated to false will stop the loop from running. What you probably wanted was:
for (var i = 0; i < arrayOfRecords.length; i++)
So when i is not less than arrayOfRecords.length, the loop will stop. Alternatively (to keep the - 1, but I tend to use the above version):
for (var i = 0; i <= arrayOfRecords.length - 1; i++)
The same goes for the nested loop.

Javascript: confused about how nested for loops work

Why do nested for loops work in the way that they do in the following example:
var times = [
["04/11/10", "86kg"],
["05/12/11", "90kg"],
["06/12/11", "89kg"]
];
for (var i = 0; i < times.length; i++) {
var newTimes = [];
for(var x = 0; x < times[i].length; x++) {
newTimes.push(times[i][x]);
console.log(newTimes);
}
}
In this example I would have thought console.log would give me the following output:
["04/11/10"]
["86kg"]
["05/12/11"]
["90kg"]
["06/12/11"]
["89kg"]
However, I actually get this:
["04/11/10"]
["04/11/10", "86kg"]
["05/12/11"]
["05/12/11", "90kg"]
["06/12/11"]
["06/12/11", "89kg"]
Is anyone able to help me understand this?
EDIT:
Thanks for all your responses!
You are redefining newTimes on every single loop and you are outputting to the console on each column push.
var times = [
["04/11/10", "86kg"],
["05/12/11", "90kg"],
["06/12/11", "89kg"]
];
var newTimes = [];
for (var i = 0; i < times.length; i++) {
for(var x = 0; x < times[i].length; x++) {
newTimes.push(times[i][x]);
}
}
console.log(newTimes);
Returns: ["04/11/10", "86kg", "05/12/11", "90kg", "06/12/11", "89kg"]
http://jsfiddle.net/niklasvh/SuEdt/
// remember that the increment of the counter variable
// is always executed after each run of a loop
for (var i = 0; i < n; i++) {
// some statement(s) to do something..
// initializes child-loop counter in the first run of the parent-loop
// resets child-loop counter in all following runs of the parent-loop
// while i is greater than 0 and lower than n
for (var j = 0; j < p; j++) {
// some statement(s) to do something..
// initializes grandchild-loop counter in the first run of the child-loop
// resets grandchild-loop counter in all following runs of the child-loop
// while j is greater than 0 and lower than p
for (var k = 0; k < q; k++) {
// some statement(s) to do something..
// or add more internal loop-nestings if you like..
}
}
}
// if the counter variables of the descendent-loops were set before the loop-nesting,
// the inner loops would only run once, because the counter would keep the value
// of the abortion condition after the loop is finished
Do this:
var newTimes = [];
for (var i = 0; i < times.length; i++) {
for(var x = 0; x < times[i].length; x++) {
newTimes.push(times[i][x]);
console.log(newTimes);
}
}
You are re-initializing newTimes each time through the loop.
You output would be appropriate if the log statement would read
console.log(times[i][x]);
Instead you output your complete new list newTimes which is initialized outside the inner loop and grows with each inner loop iteration.
The problem is in the second round of the inner loop, where it pushes the second element into newTimes. Anyway I don't understand the reason of inner loop. You can write much simpler:
var times = [
["04/11/10", "86kg"],
["05/12/11", "90kg"],
["06/12/11", "89kg"]
];
for (var i = 0; i < times.length; i++) {
console.log(time[i][0]);
console.log(time[i][1]);
}

Categories