JavaScript - Comparing List... Array Maybe?
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 Similar TutorialsHello, 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 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, i am currently working on aptana stuidio Nokia WRT to create a mobile widget. the projects requires the retrieval of data from a database. I've created a java servlet in eclipse to connect and execute query to the database. In aptana, i'm using js file and html file. i am able to connect to the servlet, process the data (split it) and store in an array to display the retrieved data on screen. But now i am facing problems to put the retrieved data (array) into a drop down list for selection. can i do it in a js file? thanks =) Hi, I'm trying to find out the min and max values of randomly generated values in a array list. Its a checkout system that randomly add a customer to a queue and does the same to remove a customer depending on a randomly generated number. Ive managed to figure out the mean of the queue but can only display the total values added to the list rather than display when the queue was at it biggest value. If anyone can point me in the right direction it would be greatly appreciated. ___________________________________________________________________ import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.ListIterator; import java.util.Queue; import java.util.Random; public class Checkout { private Queue<String> tillQueue; private int rndNumber; private int currentLen; private ArrayList <Integer>lengthList; private Random r; public Checkout() { tillQueue = new LinkedList<String>(); currentLen = 0; //current queue length lengthList = new ArrayList <Integer>(); r= new Random(); } public void simulation() { System.out.println("Time" + "\t" + "Rnd" + "\t" +"Queue Status"); for (int t=2; t<10; t++) { rndNumber =r.nextInt(6)+1; if (rndNumber==2 || rndNumber==4 || rndNumber==6) { tillQueue.add(String.valueOf(t)); currentLen++; } else if ((rndNumber==1 || rndNumber==3) && !tillQueue.isEmpty()) { tillQueue.remove(); currentLen--; } else if(rndNumber==5) { //do nothing } if(tillQueue.isEmpty()) { System.out.println(t + "\t" + rndNumber + "\t" + "Queue is empty"); } else { System.out.println(t + "\t" + rndNumber + "\t" + tillQueue.toString()); } lengthList.add(new Integer(currentLen)); } } public double CalculateMeanLength() { double mean=0.0; int sumOfLengths = 0; for (int i = 0; i<lengthList.size();i++) { sumOfLengths=sumOfLengths+(Integer)lengthList.get(i).intValue(); } mean = (double)sumOfLengths/lengthList.size(); return mean; } public int ShowMax() { int max = 0; //i know its going to be a for loop of some kind but not sure how to do it// } ----------------------------output via controller================ Time Rnd Queue Status 2 6 [2] 3 5 [2] 4 3 Queue is empty 5 5 Queue is empty 6 1 Queue is empty 7 5 Queue is empty 8 5 Queue is empty 9 4 [9] mean length = 0.375 max length = 3 //the max length here should be 1 =========================================== Thanks in advance for your help Hi, I have a php script that gets all images in my directory and outputs them as gallery[0]=firstimage.jpg, [1], [2], ... The php script is supposed to work with the javascript, so to cover all angles here is the php Code: <? //PHP SCRIPT: getimages.php Header("content-type: application/x-javascript"); //This function gets the file names of all images in the current directory //and ouputs them as a JavaScript array function returnimages($dirname=".") { $pattern="(\.jpg$)|(\.jpeg$"); //valid image extensions $files = array(); $curimage=0; if($handle = opendir($dirname)) { while(false !== ($file = readdir($handle))){ if(eregi($pattern, $file)){ //if this file is a valid image //Output it as a JavaScript array element echo 'gallery['.$curimage.']="'.$file .'";'; $curimage++; } } closedir($handle); } return($files); } echo 'var gallery=new Array();'; //Define array in JavaScript returnimages() //Output the array elements containing the image file names ?> Then this javascript uses the array for a slideshow, only I want to list each image as a small thumbnail. This will allow me to view the images on my webserver much more eye friendly. Code: <script type="text/javascript"> var curimg=0 function rotateimages(){ document.getElementById("slideshow").setAttribute("src", "images/"+gallery[curimg]) curimg=(curimg<gallery.length-1)? curimg+1 : 0 } window.onload=function(){ setInterval("rotateimages()", 2500) } </script> <div style="width: 170px; height: 160px"> <img id="slideshow" src="images/bear.gif" /> </div> I'm not sure how to go about listing all the images. I was thinking about using definition lists and only selecting the last 10 images. I can insert images into the definition description so I thought that was my best shot. I get stuck on choosing the images from the array, I attempt something like the following Code: <img src="gallery[gallery.length-11]" /> </dd> But that looks for a file, not the array. I then modified the script to get me the most recent images (if I were to add/remove images). Does this look correct? Code: <script type="text/javascript"> var curimg=0 function newestimg(){ document.getElementById("largethumb").setAttribute("src", "images/"+gallery[curimg]) curimg=(curimg<gallery.length-1)? gallery.length-1 : curimg } </script> i want to use arrays to populate an HTML list. I can populate the main list items but I can't seem to get the sub list items to work. Can anyone point out my mistake? Code: <HTML> <Body> <ul> <script> var pages = ["page1", "page2","page3"]; var subPages = ["sub1","sub2"]; for(var i = 0; i < pages.length; i++){ var page = pages[i]; document.write('<li>' + page + '</li>'); if (page == "page2"){ document.write('<ul>'); for(var i = 0; i < subPages.length; i++){ var subPage = subPages[i]; document.write('<li>' + subPage + '</li>'); } document.write('</ul'>); } } </script> </ul> </body> </HTML> 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 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"} } 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. 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 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 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! I'm trying to make my form both check that the e-mail's match and also be case insensitive when being submitted. I've figured out how to get the e-mail's to be checked to match, but can't figure out how to also make it not case sensitive. Help! This is what I have so far... Code: <head> <script type = "text/javascript"> function checkSame() { var emval1 = document.cform.email.value; var emval2 = document.cform.confirm.value; if ((emval1 != emval2) || (emval1 == "") || (emval2 == "")) { alert ("The two email addresses do not match - please re-enter them"); document.cform.email.value = "E-mail:"; document.cform.confirm.value = "Confirm Email:"; setTimeout("document.cform.email.focus()", 25); return false; } return true; } function toLowerCase() { var one = document.cform.email.value.toLowerCase(); var another = document.cform.confirm.value.toLowerCase(); if (one == another) return true; alert("Both fields must be identical."); return false; } </script> </head> <body> <form name="cform" id="cform" method="post" class="registration" onsubmit = "return checkSame()" action="form_to_email.php"> <ul> <li><label for="name">Name</label> <input type="text" name="name" id="name" tabindex="10" accesskey="1"/></li> <li><label for="email">E-mail:</label> <input type="text" name="email" id="email" tabindex="20" accesskey="2" onfocus="if(this.value=='E-mail:')this.value=''" /></li> <li><label for="confirm">Please confirm your E-mail:</label> <input type="text" name="confirm" id="confirm" onfocus="if(this.value=='Confirm Email:')this.value='' " onblur = "checkSame()" /></li> <li><input type="submit" onsubmit= "return toLowerCase()" value="Send" /><li> </ul> </form> </body> I'm having a bit of a problem processing an OPML file to load into a list widget that's included in the WebOS development kit. Say I have an OPML file like: Code: <opml version="1"> <head> <title>News</title> </head> <body> <outline text="Local News" key="local"> <outline type="link" text="Some local Blog1" URL="http://local1.com"/> <outline type="link" text="Some local Blog2" URL="http://local2.com"/> </outline> <outline text="National News" key="national"> <outline type="link" text="Some national Blog1" URL="http://national1.com"/> <outline type="link" text="Some national Blog2" URL="http://national2.com"/> </outline> <outline type="story" text="Community" URL="http://directlinktostory1.com"/> <outline type="link" text="Classifieds" URL="http://directlinktostory2.com"/> <outline type="link" text="Download More News" URL="http://newsfeed.com/getmore.ashx"/> </body> </opml> I can put each text attribute into the list widget using: Code: var tree = transport.responseXML.getElementsByTagName('outline'); for( var i = 0; i < tree.length; i++ ) { curr = tree[i]; if (!curr.hasChildNodes){ this.title = curr.getAttribute('text'); } this.category_items.push({text: this.title}); } But, what I'd like to do is divide the list into categories. To do this, I'd need to append the text attribute value of the parent node to each of the child nodes under the parent node, and in the process, tell it to push the text attribute values of the childnodes if they exist, and of the parentnodes if they do not have childnodes. So I'd be left with something looking like: Code: Local News: Some local Blog1 Some local Blog2 National News: Some National Blog1 Some National Blog2 Misc: Community Classifieds Download More News I'd also like to be able to compare the value of an attribute such as "Download More News" and have that perform a specific function. Can somebody please point me to some information on grabbing only childnodes where they exist and also comparing the value of an attribute to a string? Thank you, Doc |