JavaScript - Comparing A Value Against A Multi-dimensional Array
Hello,
I need your help. I'd like to structure and build an array like the below.: Code: var provinces = [ ['Ontario','ON'], ['Quebec','QC'], ['British Columbia','BC'], ['Saskatchewan','SK'] ]; then, id like to compare the value (x) against my array ie. Code: var x = 'Ontario' if (x matches the first value in the array 'provinces') { then let x = ON } How do you write something like this in javascript? Much thanks and appreciation for all your help, Cheers, Jay Similar TutorialsShort version: I'm having trouble with "moving subarrays" in a multidimensional associative array. Long version: (Yes, I know that there's technically no such thing as a js associative array and that I'm actually using a generic object.) This is one of those annoying questions for which significant code can't be shown. I'm fetching a JSON object from PHP and parsing it as multi-dimensional associative array that comes out with this "structure": Code: obj[regions][variables][years] = value; My presentation logic works fine for that. Year data is presented for each variable, and variables are grouped by region. For reference, if needed, the display is tabular and similar to this: Code: Regions | Variables | 2003 | 2004 | 2005 ========================================= | measure1 | abcd | efgh | ijkl ================================= county1 | measure2 | mnop | qrst | uvwx ================================= | measure3 | yzab | cdef | ghij ========================================= | measure1 | abcd | efgh | ijkl ================================= county2 | measure2 | mnop | qrst | uvwx ================================= | measure3 | yzab | cdef | ghij ========================================= | measure1 | abcd | efgh | ijkl ================================= county3 | measure2 | mnop | qrst | uvwx ================================= | measure3 | yzab | cdef | ghij ========================================= | measure1 | abcd | efgh | ijkl ================================= county4 | measure2 | mnop | qrst | uvwx ================================= | measure3 | yzab | cdef | ghij ========================================= My problem comes from trying to allow the option to reorganize the grouping - that is, turning it into regions grouped by variable. The display logic can handle it, but I can't get the array handling code right. The desired secondary structure is Code: obj[variable][region][year] = value; Some things I've tried: Code: /* obj is in the format of obj[region][variable][year] = value */ data_arr = new Array(); for (var region in obj) { for (var variable in obj[region]) { for (var year in obj[region][variable]) { /* fail one */ data_arr[variable][region][year] = obj[region][variable][year]; /* data_arr[variable] is undefined */ /* fail two */ y = obj[region][variable][year]; y_arr = new Array(); y_arr[year] = y; r_arr = new Array(); r_arr[region] = y_arr; data_arr[variable] = r_arr; /* only the values from the last iteration are displayed */ /* fail three */ y = obj[region][variable][year]; y_arr = new Array(); y_arr[year].push(y); r_arr = new Array(); r_arr[region].push(y_arr); data_arr[variable].push(r_arr); /* y_arr[year] is undefined */ } } } And then other permutations of those three. I could run through it easy if not needing the textual index, but that's actually part of my display data, so it has to stay. Can anyone help me with what I'm overlooking? I have two known methods of creating a javascript array: 1) Double brackets such as: Code: var animation_JD = [[]]; 2) Create and array then create an array inside each array element manually which is the most common method as far as I know. The problem is that the second method requires the array be be defined in size and I require a 2D array, 3D array and 4D array. Using the second method uses far to much memory to be plausible, unless there is a way to make arrays smaller by defining parts of them as integers only? Otherwise for the 1st method I described I don't know how to loop through all elements of the array such as: Code: for(group in animation_JD){ } So does anyone have another way of creating arrays, defining an array as integers only(ideally not every part of the array) to save memory, or a way to loop through arrays created in the first method? Thanks! I'm not sure why my code is working. I think it maybe because of incorrect storage of multi arrays. Can someone please take a look. Please provide advice on how to improve. Code: <script type="text/javascript"> var route ="Route A - Toronto to Barrie"; var jon, don; var businfo=[ //[destination/route, pricing, number of available tickets] ["Route A - Toronto to Barrie", 10.10, 38], ["Route B - Toronto to Peterborough", 12.30, 38], ["Route C - Toronto to Montreal", 42.00, 38], ["Route D - Toronto to Thunder Bay", 114.30, 38] ];//end multi-array businfo function determineRoute() { for(i=0; i < 5; i++){ if (route === businfo[i][0]) { jon = businfo[i]; break; } } } function setNumOfTick(ticketsordered) { don = jon; var tickettotal = don.splice(0,1); tickettotal -= ticketsordered; don.splice(0,1,tickettotal); return(2); }//end setPrice alert(setNumOfTick(35)); </script> Problem Part 1. Gather data from linux server and output to a file named data_DDMMYY Output file must contain the file name and size Part 2. Compare todays data_DDMMYY to yesterdays data_DDMMYY and output results to a file named difference_DDMMYY Output file must show the difference in size between same named files and identify new and deleted files Solution Part 1. Log into linux, use command "find . -daystart -ctime 0 -type f | xargs ls -sSh > data_DDMMYY" Sample output: Part 2. Perhaps use of an array and iterator? (my knowledge is very limited when it comes to arrays and iterators) Idea Grab file 1, go to line 1, read first string and save to variable x, read second string and save to list2 Grab file 2, using the current line in list2, look for a match. If a match is found, go to that line, read first string and save to variable y Calculate difference of x-y and save to list1, output first line of list 1 and list 2 to difference_DDMMYY If match is not found, output <string>.notFound to a new line in difference_DDMMYY Grab file 1, go to line 2, read first string and save to x, read second string and save to new line in list 2 etc ... until all lines in file 1 have been used. Then somehow I'd like to find the lines in file 2 that weren't copied to a list and output them to the difference_DDMMYY as <String>.newFile I'm sure there's some sort of for loop I can use to solve this, but as of right now I'm stumped and need ideas >.< Any and all help is appreciated. P.S. I'm new to programming, I'm not sure which language would be best to fix this problem Hi all, Forgive my ignorance, I'm quite new to Javascript... I'm looking to do two things: the first is to move elements of an array to the next index using a function. I have managed to do this like so: Code: var letters = ['h','i','j','k']; function moveElements(anArray){ var newArray = anArray; newArray.unshift(newArray[newArray.length-1]); newArray.pop(); } moveElements(letters); (this may or not be great, but it seemed to work) ... but I want the original array to reset to its original state if the function is called again (thus producing the same answer as opposed to shifting the elements again). Secondly, and this is the bit I'm really struggling with: I want to compare each letter of a string to elements within an array and display the indices. For instance: Code: var myArray = ['a', 'b', 'c', 'd', 'e', 'f']; var text = 'dead'; Hence I want the result '3,4,0,3'. I know the answer will use for and if statements but I can't wrap my head around it at all. Help would be appreciated, thank you. I'm writing a simple Chess Record keeping app (still ), and i'm having a problem with the Screen.X and Screen.Y variables to compare with the coordinate variables stored in an Array. The project is a little large, so here's the live version (on my website). Though it will only work if you run it from your local disk. http://daomingjin.googlepages.com/ScoreMate.html the zip archive of this is he http://daomingjin.googlepages.com/ScoreMatev1.zip the main JavaScript function file is he http://daomingjin.googlepages.com/Core.js the particular function in question is this: Code: var PieceThere = isPieceHere(ClosestX, ClosestY); function isPieceHere(x, y) { // Test to see if there is an Element at point x,y for (var i = 0; i < 32; i++) { if (PieceLocationXcoord[i] == x) { if(PieceLocationYcoord[i] == y) { // There is a piece there var Result = "True"; } } } return Result; } i have placed alert() boxes in many places in the code above, and i can tell the following: the function is being activated the coordinates of x and y are able to be accessed inside the function the arrays called PieceLocationYcoord and PieceLocationXcoord both have the values in them that are returned by the ClosestX and ClosestY function however, every time , the function continues to return "Undefined". I have even tried manually setting var Result = "True" inside the last if-then block, and still returns undefined. i have also tried using the alert box inside this function (before the variable return Result; is called) and still get undefined as the message from the alert box. Hi everyone I'm having a hard time, wrapping my head around an array sort+combine function. I have an array which would look somewhat (these are simplified numbers) like this Code: TestArray = [ ["222222","1"], ["222222","1"], ["222222","1"], ["333333","1"] ["111111","1"], ["000000","2"], ["111111","2"], ["111111","2"], ["222222","20"], ]; I got it as far as to be sorted like this: Code: SortedArray = [ ["000000","2"], ["111111","1"], ["111111","2"], ["111111","2"], ["222222","1"], ["222222","1"], ["222222","20"], ["222222","1"], ["333333","1"] ]; And from there to this: Code: BadlyMergedArray = [ ["000000","2"], ["111111,"1","2"], ["222222","1","20","1"], ["333333","1"] ]; But I want to end up with this: Code: MergedArray = [ ["000000","2"], ["111111","1","2"], ["222222","1","20"], ["333333","1"] ]; So the first part of the inner arrays is the first item to be sorted and combined by. After that, the smaller numbers have to do practically the same, while staying in the correct order under the first sort. I'm only a spare time programmer, and my code is probably one of the most confusing pieces of code ever written. I am assuming that this is some fairly easy stuff for one of you guys. I can post my code, but I think there's a much easier solution to it, so I wanted to see if someone can point me in the right direction, or show me how this is properly done. Thanks so much! here's to hoping! patrick/shootingpandas My array is like so... shp[0][0] = 5; shp[0][1] = "A5"; shp[0][2] = "A2"; shp[0][3] = "A1"; shp[0][4] = "A4"; shp[0][5] = "A3"; shp[1][0] = 4; shp[1][1] = "C3"; shp[1][2] = "C4"; shp[1][3] = "C1"; shp[1][4] = "C2"; shp[2][0] = 3; shp[2][1] = "E1"; shp[2][2] = "E3"; shp[2][3] = "E2"; shp[3][0] = 3; shp[3][1] = "G3"; shp[3][2] = "G2"; shp[3][3] = "G1"; shp[4][0] = 2; shp[4][1] = "I2"; shp[4][2] = "I1"; the results I am after is... shp[0][0] = 5; shp[0][1] = "A1"; shp[0][2] = "A2"; shp[0][3] = "A3"; shp[0][4] = "A4"; shp[0][5] = "A5"; shp[1][0] = 4; shp[1][1] = "C1"; shp[1][2] = "C2"; shp[1][3] = "C3"; shp[1][4] = "C4"; shp[2][0] = 3; shp[2][1] = "E1"; shp[2][2] = "E2"; shp[2][3] = "E3"; shp[3][0] = 3; shp[3][1] = "G1"; shp[3][2] = "G2"; shp[3][3] = "G3"; shp[4][0] = 2; shp[4][1] = "I1"; shp[4][2] = "I2"; so it sorts all from the second part of the array to the end in alpha-numerical order. I tried the following but i get errors about Cannot call method 'unshift' of undefined. // var shp; var shpbk; var shpbktemp; // shpbk = shp.slice(); shpbktemp[0] = shpbk[0][0]; shpbk[0] = shpbk[0].shift; shpbk[0] = shpbk[0].sort; shpbk[0] = shpbk[0].unshift(shpbktemp[0]); shpbktemp[1] = shpbk[1][0]; shpbk[1] = shpbk[1].shift; shpbk[1] = shpbk[1].sort; shpbk[1] = shpbk[1].unshift(shpbktemp[1]); shpbktemp[2] = shpbk[2][0]; shpbk[2] = shpbk[2].shift; shpbk[2] = shpbk[2].sort; shpbk[2] = shpbk[2].unshift(shpbktemp[2]); shpbktemp[3] = shpbk[3][0]; shpbk[3] = shpbk[3].shift; shpbk[3] = shpbk[3].sort; shpbk[3] = shpbk[3].unshift(shpbktemp[3]); shpbktemp[4] = shpbk[4][0]; shpbk[4] = shpbk[4].shift; shpbk[4] = shpbk[4].sort; shpbk[4] = shpbk[4].unshift(shpbktemp[4]); Hey, I'm new here, have always browsed but never created an account until now. I am an avid PHP programming but Javascript is not my thing. I am working on a module for a website of mine and I can't seem to figure thing one thing out. I have a module that competes a telephone verification and I would normally just use PHP but I am limited to the fact that I cannot alter or refresh the web page. I have a javascript module currently that people click a button and AJAX calls a serverside PHP script (which outputs a a random 4 digit code that it tells the user). That random 4 digit code is assigned to a global variable and then updating using the code ... verification_code=page_request.responseText (Output of my PHP document through AJAX) And then I have a textbox in which users input the 4 digit code (that the telephone script tells them). I have a variable called verification_input which is equal to the value of the textbox. I've been debugging this for awile now, If i write something like this Code: alert (verification_input + " code: " + verification_code); if(verification_code==verification_input){ alert('success?'); } everything works except for the success alert. The only weird thing I notice is the output of the first alert will be something like 2637 code : 2637 which the second set of numbers being on the next line. Any help would be appreciated. It's probably something simple Hello all; I am trying to use two dimensional arrays to create a grid-like slideshow. I have working code for a slideshow using one array, however I was wondering if it is at all possible to move the slideshow in all four directions (instead of just left and right). Here is the code for the left/right slideshow script: Code: <script type="text/javascript"> var present_slide=0; var images = ["../images/overworld/04-8m.png","../images/overworld/04-8n.png","../images/overworld/04-8o.png","../images/overworld/04-8p.png","../images/overworld/04-8q.png","../images/overworld/04-8r.png","../images/overworld/04-8s.png"] objImage = new Image(); function download(img_src) { objImage.src = images[img_src]; } function displaynext(shift) { present_slide = present_slide + shift; if(images.length > present_slide && present_slide >= 0) { document.images["im"].src = images[present_slide]; var next_slide = present_slide + 1; download(next_slide); // Download the next image } if(present_slide + 1 >= images.length ) { document.f1.Next.style.visibility = "hidden"; present_slide = images.length - 1; } else { document.f1.Next.style.visibility = "visible"; } if(present_slide <= 0 ) { document.f1.Prev.style.visibility = "hidden"; present_slide = 0; } else { document.f1.Prev.style.visibility = "visible";} } </script> </head> <body onload="displaynext(0)"> <form name="f1"> <img name="im" /> <div class="arrow-nav"> <input type="button" style="background:url(../images/arrow-left.png);" name="Prev" onClick="displaynext(-1);" /> <input type="button" style="background:url(../images/arrow-right.png); float:right;" name="Next" onClick="displaynext(1);" /> </div> </form> One way that I am thinking that this might work is if I create multiple row arrays and navigate them using up and down arrow keys. So, clicking left and right within the array will navigate through the contained images, and the up and down arrows will navigate through the arrays. Please let me know if this idea can be possibly implemented or if there is another way to do this. Thank you. I am trouble in comparing decimal number. var1 = 0.25 var2 = 0.50 if (var1<var2) { alert("Value is less than minimum") } else { return true; } How can I make it work. Thanks for help in advance I don't know if JavaScript is the best choice for this or maybe just Java but i want to create something were I can compare a list of names and their picks with a correct list. For example lets say this is the list of peoples picks... Code: Dan Slota New York Jets Dan Slota Cincinnati Bengals Dan Slota Pittsburgh Steelers Dan Slota Denver Broncos Dan Slota Green Bay Packers Dan Slota Atlanta Falcons Dan Slota New Orleans Saints Dan Slota Seattle Seahawks Dan Slota Indianapolis Colts Dan Slota Houston Texans Dan Slota Philadelphia Eagles Dan Slota San Diego Chargers Dan Slota Chicago Bears Dan Slota New England Patriots Danielle rossi New York Jets Danielle rossi Cincinnati Bengals Danielle rossi Baltimore Ravens Danielle rossi Tennessee Titans Danielle rossi Green Bay Packers Danielle rossi Atlanta Falcons Danielle rossi New Orleans Saints Danielle rossi St. Louis Rams Danielle rossi Indianapolis Colts Danielle rossi Houston Texans Danielle rossi Philadelphia Eagles Danielle rossi San Diego Chargers Danielle rossi Chicago Bears Danielle rossi Miami Dolphins David Fleischer New York Jets David Fleischer Cincinnati Bengals David Fleischer Baltimore Ravens David Fleischer Denver Broncos David Fleischer Green Bay Packers David Fleischer Atlanta Falcons David Fleischer New Orleans Saints David Fleischer Seattle Seahawks David Fleischer Indianapolis Colts David Fleischer Oakland Raiders David Fleischer Philadelphia Eagles David Fleischer San Diego Chargers David Fleischer New York Giants David Fleischer Miami Dolphins and here is the master list of the correct picks ... Code: Master List New York Jets Master List Cleveland Browns Master List Baltimore Ravens Master List Tennessee Titans Master List Green Bay Packers Master List Atlanta Falcons Master List New Orleans Saints Master List Seattle Seahawks Master List Indianapolis Colts Master List Houston Texans Master List Philadelphia Eagles Master List San Diego Chargers Master List New York Giants Master List Miami Dolphins After the user list is compared to the master list i need it to say the results of each user for example Code: David Fleischer 8 correct Danielle Rossi 9 correct Dan Slota 5 correct . . Sam Adams 2 correct [/CODE] What would be a good way of doing this? Any help would be appreciated Thanks. Hello all, i'm looking for a way to check if the name of the page is equal to a link inside the page being checked. for instance: inside the address bar: http://www.mysite.test.html <body> <ul> <li><a href="test.html"></a></li> <li><a href="test1.html"></a></li> <li><a href="test2.html"></a></li> <li><a href="test3.html"></a></li> </body> please advise. thanks, jav Hi I have the following script Code: function timeDifference(laterdate,earlierdate) { var difference = laterdate.getTime() - earlierdate.getTime(); var daysDifference = Math.floor(difference/1000/60/60/24); difference -= daysDifference*1000*60*60*24 document.write('difference = ' + daysDifference + ' day/s '); } var laterdate = ? ; var earlierdate = ? ; timeDifference(laterdate,earlierdate); //--></script> and would like to insert my datein and dateout values where the ? marks are above in red. I can call these variables into the form on the page using <%=Request("datein")%> but how do I call a variable into the script above ? Thanks Hello I'm trying to compare two values and return with an answer, 2 if Value 1 is greater than Value 2, 0 if Value 2 is greater than value 1 and 1 if the two values are equal. I have a script which does this when the Compare Button is selected, however I would like to remove the button so the answer is generated when the Values ae entered The script is [CODE] <html> <head> <script type="text/javascript"> <!-- function resultH1() { var str1 = document.getElementById("TotalH1").value; var str2 = document.getElementById("TotalA1").value; if(str1 != str2) { if(str1 < str2) { document.getElementById("ans").value= "2"; } else { document.getElementById("ans").value= "0"; } } else { document.getElementById("ans").value= "1"; } } // --> </script> </head> <body> <form name = "clock" action = ""> <table border = "1"> <caption>Compare</caption> <tr><td>Value 1</td> <td><input name = "TotalH1" type = "text" /> </td></tr> <tr><td>Value 2</td> <td><input name = "TotalA1" type = "text" /> </td></tr> <tr><td>Answer</td> <td><input type=text name="ans" size="3" readonly="readonly" style="background:silver"> </td></tr> <tr><td><input type = "button" value = "Compare" onclick = "resultH1()" /></td></tr> </table> </form> </body> </html> [ICODE] Can anyone advise what I need to do to remove the button Thanks I need to write a script that will search for a style attribute that matches "top: 10px;". If a match is found, it will then edit the value of that input box to "hello". So for example a webpage has: Code: <input style="top: 1px;" maxlength="20" type="text"> <input style="top: 100px;" maxlength="20" type="text"> <input style="top: 10px;" maxlength="20" type="text"> The script would edit the value of the 3rd one to "hello". I'm a beginner to javascript so my code may not make sense but bear with me please. Code: var styles = document.getElementsByTagName("input").attributes.getNamedItem("Style") for (var i = 0; i < styles.length; ++i){ if (styles.value == "top: 179px; left: 348px; width: 222px;"){styles.value="hello"} } Hello All, I'm new to javascript and trying to build a news page that has expandable/collapsible headlines. I copied some javascript to do this that works fine except that when I try to replace the clickable '+' or '-' characters with clickable images, somehow doing a comparison of the innerHTML in order to toggle it from the plus image to the minus image doesn't work. I'm assuming it has to do with how innerHTML translates tagged html vs. straight characters or text, but have tried everything and can't fix it. Any help would be greatly appreciated. Below are the script and the html in the body. Here's the script: Code: <style type="text/css"><!-- .save{ behavior:url(#default#savehistory);} a.dsphead{ text-decoration:none;} a.dsphead:hover{ text-decoration:underline;} a.dsphead span.dspimg{ font-weight:normal;} .dspcont{ display:none;} //--></style> <script type="text/javascript"><!-- function dsp(loc){ if(document.getElementById){ var foc=loc.firstChild; foc=loc.firstChild.innerHTML? loc.firstChild: loc.firstChild.nextSibling; // this is the problem area, which worked when it was like this: // foc.innerHTML=foc.innerHTML=='+'?'-':'+'; foc.innerHTML=foc.innerHTML=='<img src=../img/art/expand.png></img>'?'<img src=../img/art/collapse.png></img>':'src=../img/art/expand.png></img>'; foc=loc.parentNode.nextSibling.style? loc.parentNode.nextSibling: loc.parentNode.nextSibling.nextSibling; foc.style.display=foc.style.display=='block'?'none':'block'; }} if(!document.getElementById) document.write('<style type="text/css"><!--\n'+ '.dspcont{display:block;}\n'+ '//--></style>'); //--></script> <noscript> <style type="text/css"><!-- .dspcont{display:block;} //--></style> </noscript> And here is the html: Code: <h3><a href="javascript:void(0)" class="dsphead" onclick="dsp(this)"> <!-- this is the problem area which worked when it was like this: <span class="dspimg">+</span> --> <span class="dspimg"><img src=../img/art/expand.png></img></span>August 2, 2010 - Latest Headline</a></h3> <div class="dspcont"><br /><p>Content paragraph 1</p><p>Content paragraph 2</p> I have a Javascript function that is highlighting the menu in one of my courses. I am having a problem getting into an If statement in some cases. Here is my code: Code: function hilightCurrent() { var nav = document.getElementById('nav'); if (nav == null) { return; } var checkIndex = hreftable[__currpage]; var aObj = nav.getElementsByTagName('a'); var found = false; while ((found == false) && (checkIndex > -1)){ for(j=0; j < aObj.length; j++) { if(aObj[j].href.indexOf(index[checkIndex].href)>=0) { aObj[j].className='active'; alert("parent tag = " + aObj[j].parentNode.parentNode.parentNode.tagName); if(aObj[j].parentNode.parentNode.parentNode.getElementsByTagName == 'li'){ aObj[j].parentNode.parentNode.parentNode.className='active'; aObj[j].parentNode.parentNode.parentNode.getElementsByTagName('a')[0].className='active'; } found = true; break; } } checkIndex--; } } The alert I have in there currently is returning LI in the case where I want to get into the IF statement right below it. So the alert comes back as LI and then I am checking if it is LI but for some reason it doesn't get into that if statement. Can anyone help or have any ideas? Thanks! Hi, I have a problem related to Javascript. 1) I have a php form in which there two text boxes. 2) User enter date in these text boxes via using a calender control. 3) Dates displayed in the textbox in this format i.e: 05-11-2009 I need to compare the dates of both text boxes, but my code is not working fine. I think i need to convert these the values of both text boxes to date format, but i am unable to do this. Can anyone please help in writing the new code. Thanks I am trying to compare dates to see if they are equal, one date is passed to my function from a calendar. alert(mydate); returns "Tue Dec 22 10:00:00 EST 2009" My date that I need to compare is written dynamically out of a database and it is formatted as a string: 2009-12-22 One might think that (Date(2009-12-22) == mydate) would be true, except the time is also included ... thus it is false, but if I try to use something like this: Code: var dd = new Date(2009-12-22); if(dd.toDateString == mydate.toDateString) ...dostuff ... the dates don't equal ... and I subsequently find out that dd.toDateString actually returns "Fri Jan 22 2010" when I explicitly passed 2009-12-22 to the function. I'd simply like to compare the dates to determine if they are equal so I can pass a return value back to the calendar. The code that works, effectively returning false on all Tuesdays after today is: Code: function disallowDate(d) { var today = new Date(); if (d.getDay() == 2 && (d > today)) return false; return true; } Now I need to determine if any date selected previously is available, so I have to read them out of the database and write them dynamically to the script. Right now I have something like this, but obviously it doesn't work. Code: function disallowDate(d) { var today = new Date(); if (d == Date(2009-12-29)) return true; //this lines is written dynamically if (d == Date(2009-12-22)) return true; //this lines is written dynamically if (d.getDay() == 2 && (d >= today)) return false; return true; } thanks! |