JavaScript - Merge 2 Arrays
Hi,
I am trying to merge the values of 2 arrays. array 1 = 1, 2, 3, 4, 5 array 2 = a, b, c, d, e Resulting in: array 3 = 1-a, 2-b, 3-c, 4-d, 5-e etc both arrays that will be used originally will always of the same length. Both arrays will contain numbers Can you please help? Thanks Similar TutorialsI need to loop the alphabet and numbers 0-9 to initialize a few thousand arrays. This is for my site and is truly needed. http://www.thefreemenu.com I currently have every array written out and it takes up to much space in my .js file. The majority of my variables are empty but necessary and need to be there (including empty) for my site to work properly. Question is the last part Here's where I'm at. Code: var NewVarLetterOrNum = "a"; eval("_oneofseveralnames_" + NewVarLetterOrNum + "='this part works';"); alert(_oneofseveralnames_a); This creates the variable _oneofseveralnames_a='this part works' Code: var newArrayLetterOrNum = "a"; eval("_oneofseveralnames_" + newArrayLetterOrNum + "= new Array();"); alert(_oneofseveralnames_a) This creates the Array _oneofseveralnames_a=new Array(); and all the values in the array are null, but, now a variable like _nl_a[1]='something' can be used elsewhere because the array exists. This is all that is necessary for now because I can probably set all the variables to be blank with something like Code: i=1 while(i<=20){ _oneofseveralnames_a[i]="1-20"; i++ } alert(_oneofseveralnames_[20]); So now you have what I came to understand in the first few hours. Now to the hard part : ( I can't make multiple array's dynamically. I dont' know if its because I don't understand loops or arrays or what and its very fustrating. As for any answer you might be so kind as to provide, if you could dumb it down that would be greatly appreciated. Code: var newArray =new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z') i=1 while(i<=26){ eval("_nl_" + newArray[i] + "= new Array();"); i++ } alert(newArray[1]) // Is b, but alert(_nl_b) //I can't get _nl_b to exist, I tried everything including taking away the quotes around the letters in every test */ var _nl_a =new Array() var _img_a =new Array() var _h_a =new Array() var _r_a =new Array() var _m_a =new Array() var _yt_a =new Array() var _i_a =new Array() The above arrays are all the array _name_ parts I need but for example, a has 10 parts, a,p2_a,p3_a,.. p10_a. I need 10 pages for each letter of the alphabet and numbers 0-9 and a special all1, p2_all1 ... p10_all1. Overall 2200 arrays that need to be declared. Currently they are all written out. /* Is it possible to merge the following? Code: document.getElementById("dimensionstext").style.color = "silver"; document.getElementById("dimensionstext").style.cursor = "pointer"; So, perhaps something like: Code: document.getElementById("dimensionstext").style.color = "silver"; style.cursor = "pointer"; not sure I understand the concept behind merging two arrays together. I know that I have to make a deep copy of each array before applying the function. I know that I have to create a temp value to store the information in the arrays while I insert, but not sure how to keep in numeric order. array 1 = [3, 7, 12, 15, 22, 45, 56] and array 2 = [1, 2, 5, 17, 20] What simple code could I start with to create this.
This is my second post in codingforums.com I found help from many members that make me very happy and I take the code from Amphiluke Thanks for all Now I need another help to make two things First I want to merge 2 forms in 1, so instead of following forms: Code: <form action="#" onsubmit="location.href='http://www.mysite.com/article/'+this.indx.value; return false;"> <input name="indx" type="text" size="3" /> <input name="btn" type="submit" value="Go" /> </form> <form action="#" onsubmit="location.href='http://www.mysite.com/news/'+this.indx1.value; return false;"> <input name="indx1" type="text" size="3" /> <input name="btn" type="submit" value="Go" /> </form> I need to make it one with two radio buttons to choose which URL you want to open (Article or News) Second I need this form to be in space size 160x57 so the result will be nearly as this pictu Your help will be highly appreciated Hello all, I have have been following this merge 'How to' he http://www.astral-consultancy.co.uk/...doco.cgi?11530 which works fine. However, whatever I put below the script also ends up being merged. What do I have to enter to stop it doing that? Code: <html> <head> <style> #Slideshow1 img {height:312px; width:1000px} </style> <script type="text/javascript" src="images/slideshowmerge.js"></script> </head> <body> <h1>Merging Slideshow</h1> <script> var imgArray = new Array(); imgArray[0] = "images/image1.jpg"; imgArray[1] = "images/image2.jpg"; imgArray[2] = "images/image3.jpg"; slideshowMerge('Slideshow1','',imgArray,20,5000); </script> <br><br> <h1>WHY DOES THIS TEXT BECOMES PART OF THE MERGE?<h1> </body> </html> I'm trying to built a simple Javascript page that will serve the purpose of merging the values inputted into a form, and then using concatenation to merge these values in with other text to form several lines of commands that would be entered into a router to perform some task. So in other words, it's just a "Merge" script. I should mention that I'm just starting to learn Javascript. I actually haven't been finding Javascript as easy as I thought it would be to learn, and I think it's because there are several ways to do the same thing and I wouldn't be surprised if my problem is I'm using two different methods here...or just using the completely wrong method.... I've seen examples of using 'for' loops and arrays in forms, and I still can't get my head around that. If possible for now I just wish to call in the values and concatenate them, but maybe I do need a loop I don't know Anyway, at this point, my only wish is to be able to get the script to concatenate the values, and then later I'll add the rest of the text it will merge in with and have it write to the page instead of the console. So here is what I have right now. It only partially works (I'm only writing to the console in FireFox at the moment to debug while I test, so that is why you see console.log instead of document.write or whatever. There are 4 fields in the form, and for example, if I enter in each field one word: This is a test The ONLY result I get when submitting the form is the word "This". Then the form is cleared out of all values that were entered. I'd like it to grab all the values at once but that isn't happening. Also, you'll notice I have some 'var' statements commented out. I was trying to use them so that I can later shortcut my script by concatenating using a shorter variable. (ie - using the variable 'cluster' instead of 'document.forms.myForm.cluster.value' when I'm writing the rest of the script). However something isn't right as no matter where I try putting the var statements I get errors that those variables are undefined. I even tried defining them at some point first with some random value but that didn't help either), so that's why I commented them out for now. anyway, here is my feeble attempt at writing this script, any help or guidance would be much appreciated. Code: <!DOCTYPE html PUBLIC "-//WC3//DTD XHTML 1.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Router Subnet Commands</title> </head> <body bgcolor="#FFFFFF"> <script language="Javascript" type="text/javascript"> //var cluster = document.forms.myForm.cluster.value; //var subnetip = document.forms.myForm.subnetip.value; //var routerip = document.forms.myForm.routerip.value; //var cidr = document.forms.myForm.cidr.value; function merge() { console.log(document.forms.myForm.cluster.value) + console.log(document.forms.myForm.subnet.value) + console.log(document.forms.myForm.router.value) + console.log(document.forms.myForm.cidr.value); } </script> <form id="myForm"> <input name="cluster" id="cluster"/> cluster number <p> <input name="subnetip" id="subnetip"/> subnet IP address <p> <input name="routerip" id="routerip"/> router IP address<p> <input name="cidr" id="cidr"/> CIDR <p> <input type="submit" value="Get Commands" onclick="merge()" /> </form> </body> </html> Any advice would be much appreciated. Thanks Nat I'm trying to setup a mail merge using a gmail docs script from http://www.labnol.org/software/mail-...h-gmail/13289/. So far, it works pretty well, but I want to edit it to include the following: 1) The script should start with "Dear Noah" as opposed to "Dear Noah_Kaplan" 2) I want to add my canned response to the script so that it always appears at the bottom of the e-mail. 3) Lastly, I want the outgoing mail to be saved as individual drafts in my drafts folder in gmail before it's sent out. That way, I can decide if I want to add a sentence or two to personalize each individual email draft. Thanks in advance for your awesome help. Best, Noah By the way, here's the script I want to edit: function onOpen() { var mySheet = SpreadsheetApp.getActiveSpreadsheet(); var menuEntries = [ {name: "Step 1: Import Gmail Contacts", functionName: "importContacts"}, {name: "Step 2: Start Mail Merge", functionName: "sendEmail"}, {name: "Help / About", functionName: "showHelp"}]; mySheet.addMenu("Mail Merge", menuEntries); } function importContacts() { var groupName = Browser.inputBox("Enter the name of your Gmail Contacts group he "); var mySheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var myContacts = ContactsApp.findContactGroup(groupName).getContacts(); for (i=0; i < myContacts.length; i++) { var myContact = [[myContacts[i].getFullName(), myContacts[i].getPrimaryEmail(), "Pending"]]; mySheet.getRange(i+2, 1,1,3).setValues(myContact); } Browser.msgBox("You have successfully imported " + myContacts.length + " contacts from Gmail. Please proceed to Step 3."); } function sendEmail() { var mySheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var newLine = "<br><br>"; var emailSubject = mySheet.getRange("F2").getValue(); var emailSalutation = mySheet.getRange("F3").getValue(); var emailLine1 = mySheet.getRange("F4").getValue() + newLine; var emailLine2 = mySheet.getRange("F5").getValue()? mySheet.getRange("F5").getValue() + newLine : ""; var emailLine3 = mySheet.getRange("F6").getValue()? mySheet.getRange("F6").getValue() + newLine : ""; var emailLine4 = mySheet.getRange("F7").getValue()? mySheet.getRange("F7").getValue() + newLine : ""; var emailLine5 = mySheet.getRange("F8").getValue()? mySheet.getRange("F8").getValue() + newLine : ""; var emailBody = emailLine1 + emailLine2 + emailLine3 + emailLine4 + emailLine5; var emailSignature = mySheet.getRange("F9").getValue() + newLine; var emailYourName = mySheet.getRange("F10").getValue(); emailBody = emailBody + emailSignature + emailYourName + "<br>"; var emailReplyTo = mySheet.getRange("F11").getValue(); var myContacts = mySheet.getDataRange(); var myContact = myContacts.getValues(); for (i=1; i < myContact.length; i++) { var person = myContact[i]; if (person[1] != "" && person[2] != "OK") { var emailMsg = emailSalutation + " " + person[0] + "," + newLine + emailBody; var advancedArgs = {htmlBody:emailMsg, name:emailYourName, replyTo:emailReplyTo}; MailApp.sendEmail(person[1], emailSubject, emailMsg , advancedArgs); mySheet.getRange(i+1,3).setValue("OK"); } } SpreadsheetApp.flush(); } function showHelp() { Browser.msgBox("With Mail Merge, you can send personalized email messages to your Gmail contacts in two easy steps. For help, visit http://labnol.org/?p=13289 or send me a tweet @labnol."); } First of all thank you for reading my thread and giving time to help me. Here goes my question: How to sort this array? MY PRIORITY COLORS array: ------------ green , yellow ALL COLORS array : <---- this will be your main array. ----------------------- pink , green , orange THE RESULTS: ( the results after you sort) (Not sorted by alphabetically, but sorted by the priority colors) ---------------- green , pink , orange I hope you could help me solve this javascript sorting problem. Thank you! Code: <HTML> <HEAD> <TITLE>Listing 4.4</TITLE> <SCRIPT TYPE="text/javascript"> //DEFINE METHOD function displayInfo() { document.write("<H1>Employee Profile: " + this.data[0] + "</H1><HR /><PRE>"); document.writeln("Employee Number: " + this.data[1]); document.writeln("Social Security Number: " + this.data[2]); document.writeln("Annual Salary: " + this.data[3]); document.write("</PRE>"); } //DEFINE METHOD TO GET EMPLOYEE INFORMATION function getInfo() { var menu="0-Exit/1-Name/2-Emp. #/3-Soc. Sec. #/4-Salary"; var choice=prompt(menu,"0"); if (choice != null) { if ((choice < 0) || (choice > 4)) { alert ("Invalid choice"); this.getInfo(); } else { if (choice != "0") { this.data[choice-1]=prompt("Enter information",""); this.getInfo(); } } } } //DEFINE OBJECT function employee() { this.data = new Array(4); this.displayInfo=displayInfo; this.getInfo=getInfo; } newEmployee=new employee(); </SCRIPT> </HEAD> <BODY> <SCRIPT TYPE="text/javascript"> newEmployee.getInfo(); newEmployee.displayInfo(); </SCRIPT> </BODY> </HTML> I am currently taking a Javascript certification course, this is a exercise given (final code) I don't completely understand what is going on though, could someone explain to me Code: this.data[choice-1]=prompt("Enter information",""); that part? I don't understand why, [choice-1] I don't fully understand why an array is even needed here? Hi. I am fairly new to JavaScript. I am having some troubles with arrays. I am using Chrome 12 beta. Here is a brief version of the code I am having trouble with Code: var array=new Array() array[0]=new Array() array[0][1]=new Array() var array[0][1]=[ 3, 1, 4, 1, 5, 9, 2, 6, 5, ... ]; I do not want to use "array[0][1][n]" because my array has too many items to do that and it is just plain annoying to change the numbers that way. I get an error on the "var buffers[0][1]=[" line saying: "Uncaught SyntaxError: Unexpected token [" What is the problem in my code? Thank you ahead of time. ---mint Hi could someone help with this javascript. i dont know where to start with the script which is in bold. Program to report the results of an election. // candidates var candidateArray = ['Mr R Green...', 'Ms O Brown...', 'Ms Y Black...', 'Mr G White...', 'Ms B Grey....','Ms I Blue....', 'Mr V Pink....']; // online votes var onlineVotesArray = [21,47,23,11,56,47,30]; // paper votes var paperVotesArray = [12,4,20,11,5,4,17]; // total votes -- to be initialised below var totalVotesArray; // Add code to // -- initialise totalVotesArray with a new empty array of the same size as candidateArray // -- use a for loop to add the online and paper votes for each candidate and store the result at the corresponding position in the total votes array. Code: <script type="text/javascript"> var authors = ['Ernst Hemingway','Charlotte Bronte','Dante Alighieri','Emily Dickinson']; </script> <script type="text/javascript"> document.write('<p>The first author is <strong>'); document.write('authors[0] + '</strong> </p>'); </script> I'm getting a syntax error on the last line ? I can't see the error, I closed the strong tag, closed the p tag. Put the line in a string, why won't it write the string ? If anyone is planning on buying "ICAB4225B Automate Processes" in relation to a TAFE/College/School course, I suggest getting the teacher to actually READ the book before they use it. Tonight has been a HE-Double Hockeysticks (Not sure on language in this forum) of fixing mistakes the book has made. Double commars inplace of singles, singles inplace of doubles, single brackets, whole chunks of text that are wrong. In one place in the book it tells me to copy the text in blod and there is none. Anyway.... The code that the book has made me piece together over the last few questions has left me with: Code: <script type = "text/javascript"> { var counter = 0 var NoOfItems var ItemsNames = new Array() NoOfItems = prompt ("How many items do you want to hock?",""); for (NameCount=0; NameCount<NoOfItems; NameCount++) { ItemNames [NameCount] = prompt ("What are the names of your items?",""); } document.write ("<form name='myform'><br><table>"); while ( counter < NoOfItems) { document.write ("<tr><td><value>Enter the price of the " + ItemNames [count] + "</td><td><input type='text' name='" + ItemNames [count] + "'></td></tr>"); counter++ } document.write ("<tr><td><input type='submit' value='Submit Details' onClick='validateform'</td></tr></table></form>"); } </SCRIPT> The problem I am having it with the Array. I dont think that var = new Array is correct but thats what my text book is telling me. Any help? I have a choice when creating a new API that I would like other peoples opinions on. Do I use a single Array or Multiple arrays such as: Code: array[1][1] = "ID[56]NAME[Hello World]START[10]"; OR Code: ID[1][1] = 56; Name[1][1] = "Hello World"; Start[1][1] = 20; The API is used for animations so is very heavy work, but would using around 15 multidimensional arrays be too much and a single one be preferable??? Thanks I am working on making 2 for loops of 2 arrays to get the total of them. Then I need to get the average heights. This is for a test, yet I have not got a clue, so I need clues as I cant get it to work and I am a new coder to javascript. Code: var heights = [15,16,17,18,19]; var numbers = [2,1,6,4,2]; var average = new Array(5); average = 0 for (var heights = 0; heights <= 5; heights = heights+ 1) { total = 0 } for (var numbers = 0; numbers <= 5; numbers = numbers + 1) { total = 0 average = heights / numbers; } document.write('The average height is ' + average); Am I on the right road? I need to use this format and not functions. I have got 2 for statements but maybe I could do this with one, it is so tricky this javascript. I have 2 arrays and I would like to compare the 2 arrays. If an element in array 1 is NOT in array 2 then I would like to display that element. In this case, I should only display the letter "c" but it doesn't work and I don't know why?? Here's my code: Code: <html><head> <script type="text/javascript"> function getValue(id){ var x=new Array("a","b","c","d","e"); var y=new Array("a","b","3","d","e"); var str=""; for (var i=0; i<x.length; i++){ for (var j=0; j<y.length; j++){ if (x[i] == y[j]){ break; }else{ //Check if reach the last element in the array 2 //If yes, then display that element in array 1 b/c not in array 2 if (y[j] == y.length-1){ str += x[i]; } } } } document.getElementById(id).innerHTML = str; } function init(){ getValue("info"); } </script> </head> <body onload="init()"> <h2 id="info"></h2> </body> </html> OK first of all I will post some screenshots of the 'website' I have created so far and explain what is working and what is not working. Then I will post my code and ask for help. Below is the main screen before any action happens. The three boxes are DIV elements. The writing and dropdown menu in the first box is generated by Javascript code. Whenever a user selects an option from the dropdown menu. Information about the movie and a picture of the cover are displayed. The movie title, picture filename and movie description are all stored in three separate arrays. Now for the problem. I have created a fourth array "customerList" and left it empty. Whenever a customer clicks the reserve button it calls a function "myReserve()". This function takes the selection from the dropdown menu, then uses the push function to add the selection to the blank array. I then use the code "arrayLength = customerList.length" to get the length of the customer list. A for loop is used to cycle through the array and display the contents of the array. The problem is it only displays one selection. When reserve is clicked again the newest selection is displayed. Why will it not push the next item into the array? Javascript code, just skip through the 3 arrays at the top... the problem function is at the bottom. Code: var movieTitles = new Array(8) movieTitles[0] = "The Prestige [2006]" movieTitles[1] = "The Lives of Others [2007]" movieTitles[2] = "The Bourne Ultimatum [2007]" movieTitles[3] = "Spider-Man 3 [2007]" movieTitles[4] = "Casino Royale [2006]" movieTitles[5] = "The Illusionist [2006]" movieTitles[6] = "Sunshine [2007]" movieTitles[7] = "Zodiac [2007]" movieTitles[8] = "Quantum of Solace [2008]" var movieCovers = new Array(8) movieCovers[0] = "prestige.jpg" movieCovers[1] = "lives_of_others.jpg" movieCovers[2] = "bourne3.jpg" movieCovers[3] = "spiderman3.jpg" movieCovers[4] = "casinoroyal.jpg" movieCovers[5] = "illusionist.jpg" movieCovers[6] = "sunshine.jpg" movieCovers[7] = "zodiac.jpg" movieCovers[8] = "quantum_of_solace.jpg" var movieDescriptions = new Array(8) movieDescriptions[0] = "Two Victorian-era magicians develop a rivalry that builds into an escalating battle of tricks." movieDescriptions[1] = "Five years before its downfall, the former East-German government ensured its claim to power with a ruthless system of control and surveillance." movieDescriptions[2] = "Legendary assassin Jason Bourne uncovers mysteries of his past, which puts him in the cross-hairs of a superkiller." movieDescriptions[3] = "When Peter Parker's suit suddenly turns black it brings out the dark, vengeful side of his personality." movieDescriptions[4] = "The story examines James Bond's first mission after getting his licence to kill." movieDescriptions[5] = "Eisenheim is a stage magician who amazes the audiences of turn-of-the-century Vienna, drawing the attention of Crown Prince Leopold." movieDescriptions[6] = "Fifty years from now, the sun is dying, and mankind is dying with it. Our last hope: a spaceship carrying a device which will breathe new life into the star." movieDescriptions[7] = "A serial killer terrifies the San Francisco Bay Area and taunts police with his ciphers and letters." movieDescriptions[8] = "Seeking revenge for the death of his love, secret agent James Bond sets out to stop an environmentalist from taking control of a country's water supply." var customerList = new Array() function getMovieTitle() { var str = "<p>Available movies are contained in the list below.<br />Select a movie title to read more details.<br />If you want to add the movie to your list click the reserve option.<br /></p>" str = str + "<form action='P4_1.html' method='post'><select onChange = 'displayMovie()' name='title' id = 'droplist'><option>Choose a movie</option>" mylength = movieTitles.length //loop for each movie title in the movieTitles array for (var i=0; i<mylength; i++) { str = str + "<option>" + movieTitles[i] + "</option>" } str = str+"</select></form>" //place content into dropdown menu document.getElementById("dropdown").innerHTML = str } function displayMovie() { var i i = document.getElementById('droplist').selectedIndex - 1 var m = movieTitles[i] m = m + "<p><br><img src='"+movieCovers[i]+"'></p>" m = m + movieDescriptions[i] m = m + "<p> <a href='Javascript:myReserve()'><span id = 'res'> Reserve </span></a></p>" document.getElementById("Movie_Info").innerHTML = m } function myReserve() { var i i = document.getElementById('droplist').selectedIndex - 1 customerList.push(movieTitles[i]) arrayLength = customerList.length for (var j=0; j<arrayLength; j++) { str = customerList[j] } document.getElementById("Movie_List").innerHTML = str } HTML code, incase you want to create my files yourself to troubleshoot for me but all the problems occur in the myReserve function just above. Everything else works fine. Code: <html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"> <head> <title>P4_1</title> <script src="P4.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" media="screen" href="P4.css" /> <!--[if gte mso 9]><xml> <mso:CustomDocumentProperties> <mso:ContentType msdt:dt="string">Document</mso:ContentType> </mso:CustomDocumentProperties> </xml><![endif]--> </head> <body onload="javascript:getMovieTitle()"> <img src="logo.jpg"> <div id="dropdown" class="box1"> </div> <div id="Movie_Info" class="box2"> <p>Movie info will go here</p> </div> <div id="Movie_List" class="box3"> <p>Your movie list will go here</p> </div> </body> </html> Do arrays retain its data outside of a function. The reason why i asked this is because i created a global array and then a function. In the function i assaigned values to the global array but when i try to access the global array it gives me a "undefined" or "null" error. Code: var myArray = new Array(); var count = 0; function populate(){ for(i=0; i < 5; i++){ myArray[i] = count++; } } Im working on a program where the user enters a line of numbers and then can either sort them in order or can display the minimum number. Both those seem to work, but for some reason I keep getting three -1 values in my array. So the minimum value is always -1 and when I sort it comes back -1-1-1[numbers i enter]. I cant seem to figure out why my code is doing that. Code: private int[] buildArray(String line) { int[]arr = new int[line.length()]; arr[0] = 0; for (int i = 1; i < line.length(); i++){ arr[i] = Character.digit(line.charAt(i),10); } return arr; } private int findMin(int numbers[]) { //PRE numbers.length >= 1 int min = numbers [0]; for (int i = 1; i < numbers.length; i++){ if (numbers [i] < min) { min = numbers [i]; } } return min; } private String makeString(int numbers[]) { //PRE numbers.length >= 1 int i = 0; String s1 = new String (""); while (i < numbers.length){ s1 = numbers[i] + s1; i++; } return s1; } private void sort(int numbers[]) { for (int i = 1; i< numbers.length; i++){ int j = i-1; int temp = numbers[i]; while (j >= 0 && temp > (numbers[j])){ numbers[j+1] = numbers[j]; j--; } numbers[j+1] = temp; } } Input: 3,1,2,88 output: Min Value = -1 Line 1 Sorted = -1-1-101288 Any type of help would be very appreciated, Im very new to this still. |