JavaScript - Sort Array Of Numbers And Letters
Hi,
I have an array which is populated by a count of instances from another array, so its ends up with data like: msg = [2 x this event, 5 x that event, 17 x another event, 22 x something else] I need to sort this by the number before the 'x'. At present, a .sort() would put 1 - 9 before anything greater than 10, obviously not what I'm after. How can I make it put this array into the correct order (e.g 22 x something else, 17 x another event, 5 x that event, 2 x this event) Thanks! Ic. Similar Tutorialshi everybody, i'm using this function to allow only numbers to be written in a textbox, however i want to allow lowercase "a" and "b" also with the numbers.. is it possible with this function? Code: <script type="text/javascript"> function rakamkontrol2(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } </script> </head> <body> <input type='text' id='gostergesayfa' size="3" onkeypress="return rakamkontrol2(event)"/> Hi, I'm very new to javascript, and I'm working on a simple script that will allow me to take a string of numbers, and convert it to a word. For example: I type 00010203 into a box, and it would return abcd. I've got the above to work, however..I'd like to add a couple special characters so that when the user types in a string that contains "32" it will return a ' ' (space). For example: 000102033200010203 would return 'abcd abcd' Here's my code, as of now: Code: <script type="text/javascript"> function show_prompt() { var s = prompt("Please enter a string of numbers"); for (i = 0; i <=s.length; i = i+2) { var t = s.slice(i,i+2) var n = parseInt(t,10) + 97 document.write (String.fromCharCode(n)) } } </script> I am trying to make a JavaScript chat-bot I was using this to answer a month questions and it worked fine for what is the month after DatesA=new Array("january,February","february,March","march,April","april,May","may,June","june,July","july,Aug ust","august,September","september,October","october,November","november,December","december,January "); if (input.search("what is the next month after")!= -1) {document.result.result.value = "Sorry, I don't know."; for (i=0; i<DatesA.length; i++) { Date=DatesA[i].split('='); if (input.search(Date[0]) != -1) { document.result.result.value = Date[1];} } return true;} What is the month after May answer: June however it didn't with letters. Is there a way to write this to prevent the wrong single letter and small words from triggering Letterbefore=newArray("b=a","c=b","d=c","e=d","f=e","g=f","h=g","i=h","j=i","k=j","l=k","m=l","n=m", "o=n","p=o","q=p","r=q","s=r","t=s","u=t","v=u","w=v","x=w","y=x","z=y"); Then use this: if (input.search("what is the letter before")!= -1 || input.search("what letter comes before")!= -1) {document.result.result.value = "Sorry."; for (i=0; i<Letterbefore.length; i++) { Letter=Letterbefore[i].split('='); if (input.search(Letter[0]) != -1) { document.result.result.value = Letter[1];} } return true;} . The bot correctly answers for x y and z . It then answers V for all other letters, digits and short words What is the letter before cow answer: V Thank you for your time 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 have been working on the code for an alpha sort file and have become stumped. I need to incorporate both an insertion sort & selection sort method into my code before it will run. I attached the file I have been working on and it runs on Bluej with Java JDK. I would apretiate if you could take a look at it. If you would prefer not to download my file I have posted my code that I have been working on below. I am not familiar with the structure of an insertion sort or a selection sort mothod. I also am not clear on the point in which these methods would need to be placed in the file. Code: import java.io.*; import java.util.*; public class Words { ArrayList<String> words; public Words() { words = getData("wordlist.txt"); } public void displayWords() { for(int i=0; i<words.size(); i++) { System.out.println(words.get(i)); } } public ArrayList<String> getData(String filename) { ArrayList<String> list = new ArrayList<String>(); File myFile = new File(filename); if(myFile.exists() && myFile.length()>0) { try { BufferedReader in = new BufferedReader( new FileReader(myFile) ); String word = in.readLine(); while( word != null ) { list.add(word); word = in.readLine(); } } catch( Exception e ) {} } return list; } } Hello, I have the following script, but I'd like to sort each nested array before it is written. How can I do this? I've tried putting Games.sort(); and Games[0].sort(); in different places, but it never seems to work. Code: var Games = new Array(); //PS3 Games[0] = new Array(); Games[0][0] = "ps3list"; Games[0][1] = "Uncharted: Among Thieves"; Games[0][2] = "Prince of Persia"; Games[0][3] = "Saboteur"; Games[0][4] = "Assassins Creed"; //Wii Games[1] = new Array(); Games[1][0] = "wiilist"; Games[1][1] = "Wii Play"; Games[1][2] = "Mario Party 8"; Games[1][3] = "Okami"; Games[1][4] = "Wii Sports"; function loadGames(){ for (i = 0; i < Games.length; i++) { var list = "<ul>"; for (j = 1; j < Games[i].length; j++) { list += "<li><input type = 'checkbox' class='checkbox' name = '" + Games[i][j] + "' />" + Games[i][j] + "</li>"; } list += "</ul>" document.getElementById(Games[i][0]).innerHTML = list; } } Hi, Can i sort an array of objects in javascript?. I am having the value as Code: var myVarr = [{"name":"xyz","age":21}, {"name":"cde","age":25}]. The above array has two objects. I need to sort by age using javascript. Please help. Regards, anas I have the following array called 'datacontent' that have the following data: (4, RX33, ) (3, RX54, ) (102, RX44, ) (1, R100, Retail Branch 100) (2, RX12, ) (100, RX55, ) I want them to be sorted into this order: (1, R100, Retail Branch 100) (2, RX12, ) (3, RX54, ) (4, RX33, ) (100, RX55, ) (102, RX44, ) But it is always not sorted and it will give me as follows: (2, RX12, ) (3, RX54, ) (4, RX33, ) (100, RX55, ) (102, RX44, ) (1, R100, Retail Branch 100) My code is as follows: Code: function sortby(i) { return function(a,b){a = a[i];b = b[i];return a.toLowerCase() == b.toLowerCase() ? 0 : (a.toLowerCase() < b.toLowerCase() ? -1 : 1)} } datacontent.sort(sortby(1)); Appreciate any help. Hi all, I have an array containing numbers. I want to order this numbers contained from major to minor in order to print them .. Here's what I have done: Code: var arr = new Array(6); arr[0] = "10"; arr[1] = "5"; arr[2] = "40"; arr[3] = "25"; arr[4] = "1000"; arr[5] = "1"; function sortNumber(a,b) { return b - a; } for(var i=0;i < 6; i++){ var myarray = arr[i]; myarray.sort(sortNumber); alert(myarray); } But I get no alert and a "myarray.sort is not a function" error. What am I doing wrong? How can I solve this? Thanks a lot in advance! 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]); Hi all, I'm trying to change our shopping cart code by making a small modification. When editing a product, there is a dimensions box which currently only allows numbers. We want it to allow numbers and letters (don't ask why). The code we have is the following which we think is related to why our shopping cart won't allow letters in the box. Could someone please edit the following code to allow letters? Thank you. Code: if(isNaN(dimensionsFormat(prodWidth.value)) && prodWidth.value != "" && !sellingDP) { ShowTab(0); alert("%%LNG_EnterWidth%%"); prodWidth.focus(); prodWidth.select(); return false; } if(isNaN(dimensionsFormat(prodHeight.value)) && prodHeight.value != "" && !sellingDP) { ShowTab(0); alert("%%LNG_EnterHeight%%"); prodHeight.focus(); prodHeight.select(); return false; } if(isNaN(dimensionsFormat(prodDepth.value)) && prodDepth.value != "" && !sellingDP) { ShowTab(0); alert("%%LNG_EnterDepth%%"); prodDepth.focus(); prodDepth.select(); return false; } Hey everyone Okay so... I'm working on a site, which will include a registration form for users that wish to register. In this registration form I would like it to have an AJAX based effect, such that when the user types each letter out for his username in the field, his username will appear (letter upon letter) itself below, at the end of their unique url. To explain further:- Say I type my username to be Owen Below the field I would like it to display: http://www.mydomain.com/Owen http://Owen.mydomain.com/ As I type it. Is this possible? I've done my research, but had little luck. I'm sure it is possible as I've seen it before in a slightly different manner. Hope you can or are willing to help Thank you Owen Ayres I have a document list of several hundred drug names where some are lower case and some are all caps. I want to bold only the lower case drug names but don't want to do it manually. Is there a java script that I can apply where it automatically does that for me?
I'm working on a script to check password strength "onkeyup",so when the user enters a password after every character i call a function to check the passwords strength.I'm almost ready,but i stucked with one thing: I want to check the same characters in the password,so i can deduct some point from the score if there are identical characters. Here is my code: PHP Code: var multis = 0; for(var x = 1; x < passLength; x++) { actChar = new RegExp(password.charAt(x),"g"); multis += password.match(actChar).length; } I know it seems an easy task,but i've spent at least 6 hours with it,(the first pitfall was that i didn't know the RegExp function and took my variables into the match() function,i think you can imagine the results)and i just can't figure this out,i always get crazy results,i've tried a few more versions as well without any luck. Thx in advance for anybody who can help me! Hi wise javascript gurus, I am working on a small form that on the click of a button, it calls a function to validate a string that consists of 3 portions delimited with a dash("-") in the following format XXX-NNNN-XXX where X are letters only where N are numbers only I have to use regular expressions to validate the first portion and verify that its exactly 3 characters long that are letters only if the first portion or "plant code" is larger then 3 characters long an alert gets display also if the first portion contains alphanumeric or numeric characters an alert gets displayed, the first portion has to be in letters only. down below is my code that is not functional at the time because I know for sure the way I check for regular expressions is a bet washy but thats the only thing I was able to come up with, any help will be appreciated. thanks for making time to read my thread Code: <html> <head> <script type="text/javascript"> function validateit() { var number = document.myform.product_number.value; var charnum = number.length; if (number =="") alert("you must enter a product number, field cannot be empty"); else if (charnum < 12 || charnum > 12) alert("the product numbre has to be exactly 12 characters long"); else validate_number(number); } function validate_number(num) { var objRegEx = /^[a-z]+$/; split=num.split("-",3); if (split[0].length!=3) alert("the Plant Code portion of the Product Number has to be only three charactes long") if!(objRegEx.test(split[0]) alert("the Plant Code portion of the Product Number has to be letters only") } </script> <title>waldo's</title> <style type="text/css"> .heading{font-weigth:bold;text-align:center; font-family:"comic sans MS"} </style> </head> <body><form name="myform"> <table align="center" border="1" width="55%"> <caption style="font-family:'comic sans MS';font-size:26pt"> Waldos's WareHouse</caption> <tr class="heading"><td>Product Number</td><td>Plant Code</td><td>Production Run</td><td>Shift Number</td></tr> <tr><td><input type="text" name="product_number"></td><td><input type="text" name="plant_code" readonly></td><td><input type="text" name="production_run" readonly></td><td><input type="text" name="shift" readonly></td></tr> <tr><td><input type="button" value="Check Validity" onclick="validateit()"/></td><td align="right">Validation Date:</td><td colspan="2"><input type"text" size="47" readonly></td></tr> </table></form> </body> </html> Hey I'm trying to make a script which will check if the string which the user sent from a form contains ONLY letters. The problem is if the user entered something like this "25 years old" it allow that to be submitted. It only blocks submissions of the form if the user submits NO letters like this "12345". I want it to block submissions if at least one character isn't a letter. Here's my code: Code: var message = document.myform.formtest.value; var allowed = /[A-z+]/; if(!allowed.test(message)) { alert("The field only allows letters (a-z)."); return false; } Hi, can anyone tell me how to detect any word (a-z only, surrounded by whitespace) less than 5 letters long? Edit - this is what I have currently: Code: var RE=/\s([a-z]{1,4})\s/gi; var string="some words"; //should be turned to "words" string=string.replace(RE, ""); This is taking 4 letter chunks from the end of words. Cheers, Gus Edit - fixed (replaced \s with \b) Hello JS experts: I simply want to sort this output by date: Code: document.write(x[i].getElementsByTagName("cdate")[0].childNodes[0].nodeValue); Why can't I simply just do this? Code: document.write((x[i].getElementsByTagName("cdate")[0].childNodes[0].nodeValue).sort()); XML : Code: <item> <number>10-0057-FW</number> <title>Supervisory Contract Specialist</title> <link>http://test.usaid.com/careers/TESTgscover.html#1826296</link> <guid>http://test.usaid.com/careers/TESTgscover.html#1826296</guid> <description>10-0057-FW, Grade: GS-1102-15, Office: OAA, Opening Date: 02/26/10, Closing Date: 03/09/10, USAID Employees Only</description> <opp>1826296</opp> <office>OAA</office> <grade>SS-1102-15</grade> <odate>02/26/10</odate> <cdate>03/09/10</cdate> <eligibility>Employees Only</eligibility> <pubDate>Fri, 26 Feb 2010 09:35:42 -0500 </pubDate> </item> Partial JS: Code: var x=xmlDoc.getElementsByTagName("item"); for (i=0;i<x.length;i++) { . . . document.write(x[i].getElementsByTagName("cdate")[0].childNodes[0].nodeValue); document.write("</td><td>"); . . . Hi I'm working on displaying a list of events on my site and need to display them in ascending order. i've got an xml document that looks like this(with multiple events obviously, i've just put one here): Code: <EventList> <Event> <Title>title example</Title> <myDescription>description example</myDescription> <myLink>http://www.example.com</myLink> <dayDate>10</dayDate> <monthDate>5</monthDate> <yearDate>2010</yearDate> <EventPic>Event.gif</EventPic> </Event> </EventList> Then on my html page, I have this javascript: Code: <script type="text/javascript"> if (window.XMLHttpRequest) { xhttp=new XMLHttpRequest(); } else // Internet Explorer { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET","Events.xml",false); xhttp.send(""); xmlDoc=xhttp.responseXML; var jDate=new Date(); var jYear=jDate.getFullYear(); var jYearStr=jYear.toString(); var jMonth=jDate.getMonth()+1; var jMonthStr=jMonth.toString(); var jDay=jDate.getDate(); var jDayStr=jDay.toString(); var currentDate=jYearStr+jMonthStr+jDayStr; document.write("<div>"); var x=xmlDoc.getElementsByTagName("Event"); for (i=0;i<x.length;i++) { var theMonthDate=x[i].getElementsByTagName("monthDate")[0].childNodes[0].nodeValue; var theDayDate=x[i].getElementsByTagName("dayDate")[0].childNodes[0].nodeValue; var theYearDate=x[i].getElementsByTagName("yearDate")[0].childNodes[0].nodeValue; var theDate=theYearDate+theMonthDate+theDayDate; if (theDate>=currentDate) { document.write("<br>"); document.write("<a href='"); document.write(x[i].getElementsByTagName("myLink")[0].childNodes[0].nodeValue); document.write("'>"); document.write(x[i].getElementsByTagName("Title")[0].childNodes[0].nodeValue); document.write("</a>"); document.write("<br>"); document.write(x[i].getElementsByTagName("myDescription")[0].childNodes[0].nodeValue); document.write("<br>"); document.write(x[i].getElementsByTagName("monthDate")[0].childNodes[0].nodeValue); document.write("/"); document.write(x[i].getElementsByTagName("dayDate")[0].childNodes[0].nodeValue); document.write("/"); document.write(x[i].getElementsByTagName("yearDate")[0].childNodes[0].nodeValue); document.write("<br>"); } } document.write("</div>"); </script> Can anyone help me with sorting this? So far I have it displaying only events that are occuring after the present date(currentDate). How would I go about displaying them so that the events displayed will be in the order of the earliest date displaying first? Thanks so much, Alex I have a status page on my website, but I have multiple servers, and they cramp up the one page. I was wondering if it was possible if I could have a link that says "CSS Server Status" and it drops down with the code for the CSS server, and say for "SAMP Server Status" drops down with the code/html for the samp server. I haven't a clue about Javascript, so as much help as possible would be appretiated. |