For loop not performing last function in array (JavaScript) - javascript

The last function in the boxFill() array is not being performed. I've tried accounting for the length of the array but to no luck. (I'm very new to js, just saying). It iterates through the first four indices, and always does not perform the last index, even when I change the position of the index.
var pResult1 = document.getElementById("result1");
var pResult2 = document.getElementById("result2");
var pResult3 = document.getElementById("result3");
var pResult4 = document.getElementById("result4");
var pResult5 = document.getElementById("result5");
var pResult = [pResult1,pResult2,pResult3,pResult4,pResult5]
function checkBox() {
/*var aFlor = [2.8,"Florida","Science"];
var bGeo = [3.5,"Georgia","Business"];
var cTex = [2.3,"Texas","Health"];
var dNew = [4.2,"NewYork","Law"];
var eMic = [3.9,"Michigan","Humanities"];*/
var boxValue = document.getElementById("searchBox").value;
var boxFill = [
function(){listBox('1','Florida state Scholarship','3.5','Florida','Applied Sciences')},
function(){listBox('2','Great Achievers Scholarship','4.0','Texas','Health')},
function(){listBox('3','Helpful Future Scholarship','3.0','Georgia','Business')},
function(){listBox('4','Never Give Up Scholarship','2.0','Michigan','Humanities')},
function(){listBox('5','Times Square Talent Scholarship','3.5','New York','Law')}
]
if (boxValue.includes("f")) {
for (i=0;i<boxFill.length+1;i++) {
boxFill[i]();
}
function listBox(number,name,gpa,state,major) {
pResult[number].innerHTML =
"<dl><dt>"+number+". "+name+"</dt><dd>- minimum GPA is: "+gpa+"</dd><dd>- You must live in "+state+"</dd><dd>- For the "+major+" major!</dd></dl>";
}
Is there a direct problem with the for loop or is it something in the array itself?

i<boxFill.length+1 should be i<boxFill.length, otherwise your loop iterates one more time than there are elements.
The function gets called, but it will throw an error because it tries to access an index in pResult that doesn't exist. If you open your browser's console you should see an error such as
Cannot read property 'innerHTML' of undefined
Arrays are zero-indexed in JavaScript. That means that pResult[0] will access the first element, pResult[1] accesses the second element, etc.
Now, the last function in boxFill tries to access pResult[5], i.e. the sixth element. But pResult only has five elements!
You need pass the values 0 to 4 to listBox, not 1 to 5:
var boxFill = [
function(){listBox(0,'Florida state Scholarship','3.5','Florida','Applied Sciences')},
function(){listBox(1,'Great Achievers Scholarship','4.0','Texas','Health')},
function(){listBox(2,'Helpful Future Scholarship','3.0','Georgia','Business')},
function(){listBox(3,'Never Give Up Scholarship','2.0','Michigan','Humanities')},
function(){listBox(4,'Times Square Talent Scholarship','3.5','New York','Law')}
]
Or if you want to pass 1-5 then you need to subtract 1 when accessing the index:
pResult[number-1].innerHTML = ...;

Related

How to create a for loop to loop through JSON.stringified values determining "paste tabs" for values

Update: I need to check if a unique value is already in the pasteTab's appropriate column. My code for that is --
for (a = 0; a<coldChainRange.length;a++){
var fillWeeks = coldChainRange[a][12]
**var rxNumbers = coldChainRange[a][0]**
var pasteTab = ss.getSheetByName(fillWeeks)
//var range = pasteTab.getRange('A2:P'+pasteTab.getLastRow()).getDisplayValues()
**var array = [];
array.push(rxNumbers)**
Logger.log(array)
//Logger.log(fillWeeks)
if(fillWeeks != "Need Days Supply"){
if (pasteTab !== null && **array.indexOf(pasteTab[a][0]==-1**)){
var patientInfo = ([coldChainRange[a][0],coldChainRange[a][1],coldChainRange[a][2],coldChainRange[a][3],coldChainRange[a][4],
coldChainRange[a][5],coldChainRange[a][6],coldChainRange[a][7],coldChainRange[a][8],coldChainRange[a][9],
coldChainRange[a][10],coldChainRange[a][11],coldChainRange[a][12],coldChainRange[a][13],coldChainRange[a][14]])
pasteTab.appendRow(patientInfo)
}
}
}
}
I need to have the info not be appended if a number is already in the column, however I think the loop is iterating the length of the "pasteTab" which is determined by a week number which is two characters long
How can I create a loop that will go read JSON.stringifed values?
I am trying to loop through cell values to determine where the information should be appended to. For example, if a cell had a value of "23" it would be appended to the 23 tab.
function sendToFillWeek() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var coldChainPasteSheet = ss.getSheetByName('from looker')
var coldChainRange = coldChainPasteSheet.getRange('A2:P' + coldChainPasteSheet.getLastRow()).getDisplayValues()
for (a = 0; a<coldChainRange.length;a++){
var fillWeeks = JSON.stringify(coldChainRange[a][12])
var pasteTab = ss.getSheetByName(fillWeeks)
Logger.log(pasteTab)
}}
This is my code so far for determining the appropriate sheet. The fillWeeks produces the values I need, however the pasteTab outputs all "null" values.
for(b=0; b<fillWeeks.length;b++){
(if fillWeeks !== "Need Day Supply" ){
var patientInfo = ([coldChainRange[a][0],coldChainRange[a][1],coldChainRange[a][2],coldChainRange[a][3],coldChainRange[a][4],
coldChainRange[a][5],coldChainRange[a][6],coldChainRange[a][7],coldChainRange[a][8],coldChainRange[a][9],
coldChainRange[a][10],coldChainRange[a][11],coldChainRange[a][12],coldChainRange[a][13],coldChainRange[a][14],
coldChainRange[a][15]])
pasteTab.appendRow(patientInfo)
}
}
}
}
Essentially, I would like the information to be appended the appropriate tabs.

Javascript code saving data to 2d array throws undefined

I'm writing a script that takes values from a html table, indexes them in aray and then assign every value to a tag in a form.Codepen https://codepen.io/anon/pen/eVLKyB
My problem is that after taking all specified values from array I get
Code responsible for indexing values from table look like this:
function size_index(){
var table = document.getElementsByClassName("product_table_cus");
var index= [[],[]];
var i_index = 0;
var iter = 0; //index of first dim of array
var len = table[0].rows.length;
console.log("Len:"+len);
while(i_index<len) {
//iterate trough rows
console.log("second for, iter:"+ i_index);
var col_inner = table[0].rows[i_index].cells[0].innerHTML; //size param
var col_param = table[0].rows[i_index].cells[1].innerHTML;//size value
var col_size = col_inner.substr(col_inner.indexOf(' ')+1);
console.log("Rozmiar:"+ col_size+" Wartość:"+col_param);
// index[1][0].push("col_size");
// index[i_index][1].push(col_param);
if(col_inner.search("Rozmiar")!==-1)
{
console.log("Inner wtf:"+col_inner+"Ite:"+iter);
index[iter].push(col_inner,col_param);
console.log("Index+:"+index[iter]);
console.log("Ind:"+col_inner+"Val:"+col_param);
}
else if(col_inner.search("Rozmiar")==-1){
}
iter++;
// col_param=0;
// col_size=0;
//iterate through columns
//columns would be accessed using the "col" variable assigned in the for loop
//rows would be accessed using the "row" variable assigned in the for loop
i_index++;
}
return index;
}
You can see it in the console log:
This line of code
console.log("Inner wtf:"+col_inner+"Ite:"+iter);
Produces this output
Inner wtf:Rozmiar XXLIte:2
Your index variable has exactly two values in it.
So of course, if iter is a value greater than one, this line will cause an error:
index[iter].push(col_inner,col_param);
There are two elements in index, so index[2] will return undefined.
Your underlying problem is that [[][]] is not a two dimensional array. It is an array containing two arrays.
A safer way to do this is:
var index= [];
Then, to add an element:
index[iter] = index[iter] || [];
index[iter].push(...);

Json array getting first data

I have an array which I declared as var myclinicsID = new Array(); and now, I push some data in it,when I alert it using alert(JSON.stringify(myclinicsID)) it gives me output of ["1","2","3","4"]
Now I want to use this for my function and when I look at in console, it gives me undefined, am I doing correct by my code :
getbarSeriesData(myclinicsID[0]['clinic_id'],data[i]['datemonths']);
I want to get myclinicsID first data element which is the value is 1
myclinicsID[0]['clinic_id']
Should be
myclinicsID[0]
All you need the array index. When you say myclinicsID[0]['clinic_id'], that is trying to get the clinic_id property of "1" which is obvious undefined.
Why myclinicsID[0]['clinic_id'] ? As there is nothing like clinic_id in your array.
Your array is single dimensional array. Hence, you can directly access the first element from an array using myclinicsID[0].
DEMO
var myclinicsID = new Array();
myclinicsID[0] = 1;
myclinicsID[1] = 2;
myclinicsID[2] = 3;
myclinicsID[3] = 4;
function getbarSeriesData(clientID) {
console.log(clientID);
alert(clientID);
}
getbarSeriesData(myclinicsID[0]);

javascript push inside init method not updating array length correctly

I'm trying to create an array of objects with an init method, and when I push an object into an array, it should push another object into the array, while keeping track of the length of the array.. The problem is that it doesn't update the length of the array until all the objects have been added, so when each object tries to grab the length, they all get 0.
How can I have it update the length in this process?
here's the jfiddle: http://jsfiddle.net/bg3Vg/13/
As you can see it gives a message showing that the grouptotal is 5, but it seems as if the total counts up from the last pushed object to the first.. I need it to work in the correct order so that the last pushed object can retrieve the correct length.
var colorGroup = [];
var grouptotal = 0;
colorGroup.push(new groupdata(0) );
alert(grouptotal+","+colorGroup[colorGroup.length-1].parent);
function groupdata(parent) {
this.parent = parent;
this.refnum;
this.init = function()
{
grouptotal++;
this.refnum = colorGroup.length;
if(grouptotal<5)colorGroup.push(new groupdata( this.refnum ) );
}
this.init();
}
edit:
ok, I found a way to solve my problem I think. Let me know how horrid this solution is..http://jsfiddle.net/EqAqv/1/
var colorGroup = [];
var grouptotal = 0;
var colorGroupWait = [];
colorGroup.push(new groupdata(0) );
while(colorGroupWait.length>0){
var newcolorGroup = colorGroupWait.shift();
colorGroup.push(new groupdata(newcolorGroup) );
}
alert(grouptotal+","+colorGroup[colorGroup.length-1].parent);
alert(grouptotal+","+colorGroup[colorGroup.length-2].parent);
function groupdata(parent) {
this.parent = parent;
this.refnum;
this.init = function()
{
grouptotal++;
this.refnum = colorGroup.length;
if(colorGroup.length<5)colorGroupWait.unshift( this.refnum );
}
this.init();
}
JavaScript arrays do update the length property as soon as you push something on to them. The problem is that you're recursively calling the constructor, so the statement this.refnum = colorGroup.length is getting executed for each initialization BEFORE any push occurs.
In other words, JavaScript is working as expected.
Is there any particular reason you are doing it in this convoluted manner? It be more straightforward (and achieve the result you're looking for) if you just did it like this:
for(grouptotal=0; grouptotal<5; grouptotal++){
colorGroup.push( new groupdata(grouptotal) );
}
Also, it is convention in JavaScript to name object constructors with a capital letter. So, while groupdata is not invalid syntax, it is confusing: you should consider naming it Groupdata.
#EthanBrown has already pointed out the problems. Here is a solution that puts all the logic in the constructor, and avoids the problem of pushing the instance after having it created from a wrong number.
function GroupData(parentnum) {
this.parentnum = parentnum;
this.refnum = GroupData.colorGroup.length;
GroupData.colorGroup.push(this);
if (GroupData.colorGroup.length < 5)
new GroupData(this.refnum);
}
GroupData.colorGroup = [];
var root = new GroupData(0);
alert(GroupData.colorGroup.length+", "
+GroupData.colorGroup[GroupData.colorGroup.length-1].parentnum);

access javascript array element by JSON object key

I have an array that looks like this
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}]
I would like to be able to access the Count property of a particular object via the Zip property so that I can increment the count when I get another zip that matches. I was hoping something like this but it's not quite right (This would be in a loop)
Zips[rows[i].Zipcode].Count
I know that's not right and am hoping that there is a solution without looping through the result set every time?
Thanks
I know that's not right and am hoping that there is a solution without
looping through the result set every time?
No, you're gonna have to loop and find the appropriate value which meets your criteria. Alternatively you could use the filter method:
var filteredZips = Zips.filter(function(element) {
return element.Zip == 92880;
});
if (filteredZips.length > 0) {
// we have found a corresponding element
var count = filteredZips[0].count;
}
If you had designed your object in a different manner:
var zips = {"92880": 1, "91710": 3, "92672": 0 };
then you could have directly accessed the Count:
var count = zips["92880"];
In the current form, you can not access an element by its ZIP-code without a loop.
You could transform your array to an object of this form:
var Zips = { 92880: 1, 91710: 3 }; // etc.
Then you can access it by
Zips[rows[i].Zipcode]
To transform from array to object you could use this
var ZipsObj = {};
for( var i=Zips.length; i--; ) {
ZipsObj[ Zips[i].Zip ] = Zips[i].Count;
}
Couple of mistakes in your code.
Your array is collection of objects
You can access objects with their property name and not property value i.e Zips[0]['Zip'] is correct, or by object notation Zips[0].Zip.
If you want to find the value you have to loop
If you want to keep the format of the array Zips and its elements
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}];
var MappedZips = {}; // first of all build hash by Zip
for (var i = 0; i < Zips.length; i++) {
MappedZips[Zips[i].Zip] = Zips[i];
}
MappedZips is {"92880": {Zip: 92880, Count:1}, "91710": {Zip:91710, Count:3}, "92672": {Zip:92672, Count:0}}
// then you can get Count by O(1)
alert(MappedZips[92880].Count);
// or can change data by O(1)
MappedZips[92880].Count++;
alert(MappedZips[92880].Count);
jsFiddle example
function getZip(zips, zipNumber) {
var answer = null;
zips.forEach(function(zip){
if (zip.Zip === zipNumber) answer = zip;
});
return answer;
}
This function returns the zip object with the Zip property equal to zipNumber, or null if none exists.
did you try this?
Zips[i].Zip.Count

Categories

Resources