JavaScript - Trouble Re-organizing Multi-dimensional Array
Short 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? 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 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> 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 Hi i start of with a some csv data and convert this into an array. The resulting array looks like the following [["Apple", "64"], ["Banana", "20"], ["pear", "12"], ["Orange", "16"]] But i need this to be formatted as below without the quotes around the second value. [["Apple", 64], ["Banana", 20], ["pear", 12], ["Orange", 16]] Im not sure how to achieve this. I guess i need to loop through the array and strip out the quotes but im failing to get this working. Help! I have an array, I can not figure out how to take myTemplateholder = myTemplateholder.replace(" "+children[child],children[child]+"<div id='questionRadio'><input type='radio' name='answer' value='Y' /> Y <input type='radio' name='answer' value='N' /> N <input type='radio' name='answer' value='NA' /> N/A<br /></div>");} to display to separate lines. Right now, if there is more than one value, it gets added together. Here's the rest of the code: Code: function showText(){ // var myTemplateholder = document.getElementById('myTemplateholder').innerHTML; // document.getElementById('showMe').innerHTML = myTemplateholder; var children = new Array('Chills','Fatigue','Fever','Health History','Screening','Eye-ROS','Skin','Assessment','General Appearance','Vitals','Hearing','200','300','400','500'); var myTemplateholder = $('#myTemplateholder').text(); myTemplateholder = myTemplateholder.replace("Sections ",""); myTemplateholder = myTemplateholder.replace("History","<div id='templateHeader'>History</div>"); myTemplateholder = myTemplateholder.replace("ROS","<div id='templateHeader'>ROS</div><br>"); myTemplateholder = myTemplateholder.replace("Exam","<div id='templateHeader'>Exam</div>"); myTemplateholder = myTemplateholder.replace("ICD9","<div id='templateHeader'>ICD9</div>"); for(child in children) { myTemplateholder = myTemplateholder.replace(" "+children[child],children[child]+"<div id='questionRadio'><input type='radio' name='answer' value='Y' /> Y <input type='radio' name='answer' value='N' /> N <input type='radio' name='answer' value='NA' /> N/A<br /></div>"); } $('#showMe').html(myTemplateholder); } I'm totally stuck! Thanks for bearing with a newbie - any help would be greatly appreciated. I'm just a beginner with JS and having trouble with the code for my array and FOR loop. I'd like the names of these animals to be listed on separate lines. Am I way off here? I wasn't sure if the for statement had to be within a function. I've spent hours trying to figure this out and appreciate any help. <script type="text/javascript"> var animal = new Array(4); animal[0] = "dog"; animal[1] = "cat"; animal[2] = "bird"; animal[3] = "rabbit"; var counter = 0; function writeAnimal () { for (var counter = 0; counter== 4; counter++) { document.write(animal[0]); document.write("<br />"); } } </script> I am trying to sort an array of strings based on the location of a string called "this.oText.value" inside an array of strings called "aList." If "this.oText.value" comes earlier in an entry in aList (call it "a") than another entry "b", I want "a" to appear before "b". Clearly, there is something very wrong with my code. It really isn't doing anything as of right now. Code: aList.sort(sortArray); function sortArray(a,b) { if(a.toLowerCase().indexOf(this.oText.value.toLowerCase()) < b.toLowerCase().indexOf(this.oText.value.toLowerCase())) return 1; else if(a.toLowerCase().indexOf(this.oText.value.toLowerCase()) > b.toLowerCase().indexOf(this.oText.value.toLowerCase())) return -1; else return 0; } All I am trying to pull the data from an array and place it in a table. If I assign index 0 it works as desired. I then placed it inside a foor loop and changed the index to a variable and I get "undefined". Here is the code snipet: document.write("<table width='500'>"); document.write("<tr><td width='75%'>Product:</td><td width='25%' align='center'>Cost</td></tr>"); for (i=0; i<(itemPrice.length); i++); { document.write("<tr><td>" + itemName[i] + "</td><td align='right'>" + itemPrice[i] + "</td></tr>"); totalcost = totalcost + itemPrice[i]; } document.write("<tr><td>The total is:</td><td align='right'>" +"$ "+totalcost+ "</td></tr>"); document.write("</table>"); compared to some of the samples I have seen I apologize if this is too elementary. rneaul Could someone take a look at this and tell me what I am doing wrong please? I have an onSubmit function that calls the following code. It works fine spitting out the return values, but the section with the "textareas for" statement is displayed after everything else. (I understand why) However, I want it to display in the order with the rest of the fields. Ideally it should be a part of the "inputArray for" statement. Is there an easy way to join these two for statements and spit everything out in the order from the original form? Thanks Code: <script> function showComposer() { var textstring = ''; var textAreaArray = ''; var textareas = document.repairform.getElementsByTagName("textarea"); var inputArray = document.repairform.getElementsByTagName("input"); for (i=0;i<inputArray.length;i++) { if (inputArray[i].getAttribute('class') == 'info') { textstring += "<table><tr><td><strong>" + inputArray[i].name + " : </strong></td>" + "<td>" + inputArray[i].value +"</td></tr></table>"; } else if((inputArray[i].getAttribute('type') == 'text') || (inputArray[i].getAttribute('type') == 'radio' && inputArray[i].checked)) { textstring += "<table><tr><td><strong>" + inputArray[i].name + " : </strong></td>" + "<td>" + inputArray[i].value +"</td></tr></table>"; } } for (i=0;i<textareas.length;i++) { textAreaArray += "<table><tr><td><strong>" + textareas[i].name + " : </strong></td>" + "<td>" + textareas[i].value +"</td></tr></table>" + '\n'; } var stringArray = textstring.concat(textAreaArray); var composer = new NKMailComposer(); composer.setRecipient(""); composer.setSubject("ESTIMATE SHEET AND REPAIR ORDER"); composer.setBody (stringArray, 1); composer.show(); document.repairform.submit(); } </script> Array.prototype.each = function (fn) { this.map(fn) } This is my each function that works great in every other browser but IE. UGH! What am I doing wrong? the error points to the this in the function. Is it that IE doesn't like map? Has anyone seen this before? I thought my code was correct. Works perfect in FF, chrome and opera. the canvas text doesn't work in opera, but it does render the features so the each function is working. I'll post the code if needed, but it's huge. here's the script running. http://www.pdxbusiness.com/canvas/golf/ Hola, I have a problem where I have a number of random set of elements that have a fixed rule for class name. I want to move them to a container element according to this class name. So for example the site generates Code: <p class="dog-1"></p> <p class="dog-2"></p> <p class="cat-1"></p> <p class="dog-3"></p> My output would be ideally Code: <div class="dog"> <p class="dog-1"></p> <p class="dog-2"></p> <p class="dog-3"></p> </div> <div class="cat"> <p class="cat-1"></p> </div> When searching for a solution, all I could find was simple ordering of elements according to class... Thanks 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]); 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 have a problem with some forms and utilizing the proper code to make them work. Need some help if anyone out there has some working knowledge could help let me now, anyone ?? Eric I will post the code and the problem if someone would chim in thanks Hi there, I have a couple of scripts which both do exactly what I want, but when I try use them both at the same time only one of them will work, could you tell me if i need to change anything in them to get them both to work at the same time or if im missing something really simple? Thanks Script 1 Code: <script type="text/javascript"> var imgPaths = ['pic1.jpg', 'pic2.jpg', 'pic3.jpg', 'pic4.jpg', 'pic5.jpg']; //preload the images var imgObjs = new Array; for(var i=0; i < imgPaths.length; i=i+1) { imgObjs[i] = new Image(); imgObjs[i].src = imgPaths[i]; } function togglePic(num) { if(currPic == 0 || currPic != num) { document.getElementById("image").src = imgObjs[num].src; currPic = num; } else { document.getElementById("image").src = imgObjs[0].src; currPic = 0; } } //load the default image window.onload=function() { document.getElementById("image").src = imgObjs[0].src; currPic = 0; //flag storing current pic number } </script> Script 2 Code: <script type="text/javascript"> window.onload=function () { setStyles(); }; function setStyles() { ids = new Array ('style1','style2','style3','style4'); for (i=0;i<ids.length;i++) { document.getElementById(ids[i]).className=''; document.getElementById(ids[i]).onclick=function() { return Cngclass(this); } } } function Cngclass(obj){ var currObj; for (i=0;i<ids.length;i++) { currObj = document.getElementById(ids[i]); if (obj.id == currObj.id) { currObj.className=(currObj.className=='')?'selected':''; } else { currObj.className=''; } } return false; } </script> HTML Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> </head> <body> <div id="style"> <div id="styleimage"> <img src="" id="image" width="610" height="229" /> </div> <div id="stylenav"> <ul> <li id="style1"><a href="#" onclick="togglePic(1); return false">style 1</a></li> <li id="style2"><a href="#" onclick="togglePic(2); return false">style 2</a></li> <li id="style3"><a href="#" onclick="togglePic(3); return false">style 3</a></li> <li id="style4"><a href="#" onclick="togglePic(4); return false">style 4</a></li> </ul> </div> </div> </body> </html> Hello, I would like to add multi-language support on the website. So far i have the following code which enables a drop down menu. I would rather prefer a flags instead of a drop down menu. Please help. Thank you very much. PHP Code: <div id="google_translate_element" class="right"></div> <script> function googleTranslateElementInit() { new google.translate.TranslateElement({ pageLanguage: 'en', includedLanguages: 'en,fr,de,it,es', gaTrack: true, gaId: 'UA-28770952-1', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL }, 'google_translate_element'); } </script><script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script> Hi i am working on a website project.. in which i have like.. for the menu.. i have a horizontal menu.. with three tabs for eg... Home , about us, contact us and.. when i click on the Home tab, i need a horizontal submenu with four or five links.. say for eg : menu1,menu2,menu3,menu4,menu4 and menu5 and when i click on menu1 i need a vertical menu on click of of menu1. so i need two horizontal menu and one vertical menu. i have attached a sample image of my menu. please have a look. Can i do this in javascript.. I need to do this using html , css or jquery.. How do i ... Please help me Hey everyone, I need some help with a function. I'm using ajax to grab a response from a PHP page, on success, the ajax sets a variable. After the line that calls the ajax function is the line the returns the variable (a global variable). Problem is, because the variable is returned right after the ajax function is fired, it doesn't give the ajax enough time to set the variable. The work around I've thought about would be using the ajax function as a variable, and returning that variable in the initial return line. Could anyone either help me with a better solution, or tell me what I'm doing wrong? Here's some code for reference: The function that will return the response I'm trying to collect: Code: function lt_ajaxGet(hash) { var params = "hash=" + escape(encodeURI(hash)); makePOSTRequest('hash.php?get', params); return ajax_response; } The ajax code: Code: if(http_request.status == 200){ ajax_response = http_request.responseText; } hi i am writing a code which needs multi event that's not my problem but it is about mouse event my html is like this Code: <form> d:<input type='text' name='dlink' id='dlink' onkeypress='a()'><br /> m:<input type='text' name='mlink' id='mlink'> </form> i want to perform any changes on dlink to mlink for example i'm using onkeypress so if a user used mouse [right click and then paste] it not works any event like onmouseover or onfocus or ... do not solve my problem i found out that IE has onpaste but other browser not so help me what should i do? |