JavaScript - Custom Sort
I already have a sort function that but wish to provide my users with the ability to specify custom sorts - days of the week, months etc.
Assuming that I have a function that will return day of week (ie 'Mon' = 0, "Tue" = 1, "Wed" = 2 ... etc) can anyone show me how I would incorporate this into a sort routine? Many thanks in advance should you respond to this. Similar TutorialsHi I have a table that sorts in jquery and I have one column that I would like to always remain the same while the other columns sort around it. What I want is for the order of the column to always be Great, Bad, Failure while every other column can be sorted and I don't want to the column to sort alphabetically. What is the easiert way for me to do this?
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 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>"); . . . 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. I check the web and they only show you how to sort the whole array. I would like to be able to sort the subset of the 2D array. Here's my array. Code: var myArray=new Array( new Array("af","ad","az","ab"), new Array("bc","bd","bg","bb","bx"), new Array("cf","ck","ca","cv","co"), new Array("dd")); How would I sort the sub array independently. So only the a's together, then only the b's together, etc. thanks Hi, OK, I know a bubble sort is very inefficient for sorting values but I have to do it as part of some coursework. I have the code working, i.e. it produces a sorted list of numeric values but the process of sorting the values is wrong. Below is my complete script. Code: <HTML> <HEAD> <TITLE> A program to sort an array using a bubble sort </TITLE> <SCRIPT> /*A function to sort an array. Function takes an array of numbers as an argument. Function returns a new array with the same elements as the argument array, sorted into ascending order*/ function bubbleSort(arrayToSort) { // declare and initialise a variable to hold the length of the argument array var length = arrayToSort.length; //declare an array to be returned by the function var returnArray = new Array(length); //copy each element of the argument array to the return array for (var i = 0; i < length; i = i + 1) { returnArray[i] = arrayToSort[i]; } // PLACE YOUR CODE FOR THE FUNCTION HERE /* */ for (var j = 0; j < returnArray.length - 1; j = j + 1) { for (var k = j + 1; k < returnArray.length; k = k + 1) if (returnArray[j] > returnArray[k]) { var temp; temp = returnArray[j]; returnArray[j] = returnArray[k]; returnArray[k] = temp; document.write('Array after each swap ' + returnArray + '<BR>') } } return returnArray; } /* a function for testing the bubbleSort() function. Function assigns an array to a variable Displays elements of unsorted array in order Invokes bubbleSort() function with the array as the argument Displays elements of sorted array in order Function takes no arguments. Function returns no value.*/ function bubbleTest() { var unsortedArray; //array to accept numbers to be sorted var sortedArray; //array to show sorted numbers // the array of values to be sorted unsortedArray = [4,3,2,1]; // TO DO TASK 3 (iv) // PLACE YOUR FUNCTION CODE HERE /*Write out the array 'unsortedArray'*/ document.write('A program to sort a series of numbers using the Bubble Sort method.' + '<BR>' + 'Unsorted array ' + unsortedArray + '<BR>'); /*Assign the results of the 'bubbleSort' function to the array 'sortedArray'*/ sortedArray = bubbleSort(unsortedArray); /*Write out the array 'sortedArray'*/ document.write('Sorted array ' + sortedArray + '<BR>'); /* The arrays below are for use in Task 4 (iii) and Task 5(iii) and can be ignored in Task 3 DATA SET 1 [8,4,6,2,10,5,3,7,1,9] DATA SET 2 [1,5,2,8,6,7,10,9,4,3] DATA SET 3 [ 6,3,8,7,2,9,10,4,5,1] DATA SET 4 [7,5,2,10,6,8,4,3,9,1] DATA SET 5 [9,4,1,10,5,2,3,8,7,6] */ } /*Test area for bubbelSort array*/ //var unsortedArray = [9,7,2,10,1,4,8,6,5,3]; //Test arguments //bubbleSort(unsortedArray); // invoke bubbleTest() to test the bubbleSort() function bubbleTest(); </SCRIPT> </HEAD> <BODY> </BODY> </HTML> OK, the problem is that on after the first pass, the numbers should be as follows: 3,2,1,4 The biggest number always ends up in it's place after each pass. My code above outputs the numbers after the first pass: 3,4,2,1 You will notice it is probably an inefficient way of writing the code. We have to only use code we have learnt Sorry for the long post!! 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 http://jsfiddle.net/FZ44M/3/ Thats my jsfiddle. I'm trying to get the gallerynav to sort the thumbnails based on their class. It does not work at all. I've gone over line by line but I can't see the mistake. When I run JSLink i get the error: Error: Problem at line 37 character 14: Cannot set property 'first' of undefined Implied global: $data 13,14, arr 14,15,25, jQuery 28, $ 30 Unused variable: read_button 30 "$", r 32 "read_button" I appreciate any help. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script> window.onload = function(){ document.getElementById("t").innerHTML = "<table border='1' id='myTable'>" + "<tr><td>" + names.join("<tr><td>") + "</td></tr>" + "</table>"; } var names = ["Marble","Jarque","Dino","Pineapple"]; function abc(){ if(document.getElementById('myTable').rows[0].cells[0].innerHTML==names[0]){names.sort()} else if(document.getElementById('myTable').rows[0].cells[0].innerHTML==names[2]){names.sort().reverse()} else {names.sort()} document.getElementById("t").innerHTML = "<table border='1' id='myTable'>" + "<tr><td>" + names.join("<tr><td>") + "</td></tr>" + "</table>"; } </script> </head> <body> <div id="t"></div> <input type="button" value="sort" onclick="abc()" /> </body> </html> First time sort: no problem But when it comes to the blue-highlighted parts It cannot do the sort().reserve() What's wrong with the codes? We list our branches on our webpage, but I want people to be able to search for the nearest ones. This is the form I built as a place holder... but I'm sure I need a "little something" to go along with it. ha ha ha. Code: <form class="login">   <label class="white"><b>Zip Code</b><br />   <input name="zip" type="text" maxlength="5" size="10"/> </label> <br /><br /> <label>   <input type="submit" name="submit" id="submit" value="Go!" class="btn" /> </label> </form> I would like to sort them in order of closest to furthest (or even just display the top 5)... where would I find something like that? I seem to be having a difficult time with my searches in google and otherwise. Anyone have any ideas? Basically what I have here in the following code is 15 random numbers that I am supposed to use the bubble and selection sort algorithm to sort. How can I go about getting the numbers to be sorted using selection sort I have already done the bubble. Thanks Code: <html> <body> <script language ="javaScript"> var array = new Array(15); function genNumbers(listbox){ var i; for(i= 0; i < array.length; i++) { array[i] = Math.random()*15; array[i] = Math.round(array[i]); } updateList(listbox); } function sortNumbers(listbox) { var x, y, holder; for(x=0; x < array.length; x++) { for(y=0; y< (array.length-1); y++){ if(array[y] > array[y+1]){ holder = array[y+1]; array[y+1] = array[y]; array[y] = holder; } } } updateList(listbox); } function updateList(listbox) { var i; for(i = 0; i< array.length; i++){ if(listbox.options[i] == null) { listbox.options[i] = new Option(array[i]); } else{ listbox.options[i].text = array[i]; } } } </script> <form> <center> <select name = "ranlist" size "10" style = "width: 100px"> </select> <br><br><br> <input type = "button" value = "Generate" onClick = "genNumbers(this.form.ranlist);"> <input type = "button" value = "Bubble Sort" onClick = "sortNumbers(this.form.ranlist);"> </form> </body> </html> 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; } } Hello, I have the following object: Code: var layers = { photo1 : { index : 1, xPos : 63, yPos : 48, angle : 0 }, background : { index : 0, xPos : 278, yPos : 163, angle : 0 } } How can I sort the objects by the index property? Code: for(var layer in layers.sort(???)) { } Thx Very Much! Hey guys my question is related to sort table This is the code for the table: PHP Code: $result = $conn->query("SELECT query, link, pro,pro_update,ana,ana_update,cell,cell_update,cellother,cellother_update,gen,gen_update,genother,genother_update,author,author_update,other,other_update,date,id FROM mailing_list WHERE email = '$email' ORDER BY $order LIMIT $start_row, $max_per_page;"); echo "<table class=\"sortable\" id=\"query_quick2\" width=\"100%\" >\r\n"; echo "\t<tr><th class=\"sorttable_alpha\" >Updated Query</th><th width=\"10\" class=\"sorttable_alpha\" >Link</th> <th class=\"sorttable_alpha\" >Promoter Locus</th><th class=\"sorttable_alpha\" >Update</th> <th class=\"sorttable_alpha\" >Anatomical Area</th><th class=\"sorttable_alpha\" >Update</th> <th class=\"sorttable_alpha\" >Cell Type</th><th class=\"sorttable_alpha\" >Update</th> <th class=\"sorttable_alpha\" >Other Cell Type</th><th class=\"sorttable_alpha\" >Update</th> <th class=\"sorttable_alpha\" >Genetic Background</th><th class=\"sorttable_alpha\" >Update</th> <th class=\"sorttable_alpha\" >Other Gen. Back.</th><th class=\"sorttable_alpha\" >Update</th> <th class=\"sorttable_alpha\" >Author</th><th class=\"sorttable_alpha\" >Update</th> <th class=\"sorttable_alpha\" >Other</th><th class=\"sorttable_alpha\" >Update</th> <th class=\"sorttable_mmdd\" >Date</th><th class=\"sorttable_nosort\" ></th><th class=\"sorttable_nosort\" ></th>\r\n"; if($result->num_rows){ while ($row = $result->fetch_array()){ $RowCount ++; $row_color = ($RowCount % 2) ? $color1 : $color2; echo "<form method = \"post\" action=\"{$_SERVER['PHP_SELF']}\">"; echo "\t<tr id=\"{$row['id']}\" class=\"$row_color\" > <td>{$row['query']}</td><td>{$row['link']}</td> <td>{$row['pro']}</td><td>{$row['pro_update']}</td><td>{$row['ana']}</td> <td>{$row['ana_update']}</td><td>{$row['cell']}</td><td>{$row['cell_update']}</td><td>{$row['cellother']}</td> <td>{$row['cellother_update']}</td><td>{$row['gen']}</td><td>{$row['gen_update']}</td><td>{$row['genother']}</td> <td>{$row['genother_update']}</td><td>{$row['author']}</td><td>{$row['author_update']}</td><td>{$row['other']}</td><td>{$row['other_update']}</td> <td>{$row['date']}</td> <td><input type=\"submit\" name=\"edit_mail\" value = \"Edit\"/></td> <td><input type =\"hidden\" name = \"id\" value=\"{$row['id']}\"/></td> <td><input type=\"submit\" name=\"delete_mail\" value =\"Delete\"/></td> </tr>"; echo "</form>"; } } echo "</table>"; This is an excerpt of the script which deletes the specific entry: PHP Code: } elseif(isset($_SESSION['user_id']) AND isset($_POST['delete_mail'])){ //user is deleting existing queries $connect=db_connect_2(); $id = mysqli_real_escape_string($connect, $_POST['id']); $sql2 = "DELETE FROM mailing_list WHERE id='$id'"; $result = mysqli_query($connect, $sql2) or mysqli_error($conn); $msgs[] = "Queries DELETED successfully."; $body = "account.php"; } I can delete the specific entry like usual at the beginning but right AFTER i sort the table by clicking a column heading, say, promoter locus, (using sortable.js) and then when i try to delete a specific entry, problem arises. Instead of deleting the entry i want, it always deletes the LAST entry. Now as you can see, i select a specific value for $id, using post method from a form But shouldn't the value of $id point to the entry i want to delete when i click the "delete" button near it? (i mean it works fine before i sort the table) Any help would be greatly appreciated Thanks. My problem is in the drop down menus for site names, we have hundreds of sites and unfortunately the menu is not sorted 0-1 then A-Z and I would love it to be sorted like that. I have tried to do my homework and understand java / javascript but I just can't stand it and I feel it is too complicated for me. The good news is I used to be a good ASP/vbscript programmer about 12 years ago so I have the "common sense" of understanding how to apply something similar on other pages, because I have lots of drop down menus that I need to sort. I need your help in the attached file please. I need someone to simply highlight for me where in the javascript is fetching the site names from the DB and what needs to be added to sort them. Please identify it inside the file by either different color or bold font. Once I see it i will be able to figure out how to apply it in general to the other menus in the other pages. Thank you in advance. To set the stage I'm working on a set of D&D tools. I have a players list that is "draggable" with jQuery and an encounter list that is "droppable." The idea is to drag the players over to the encounter list as I need them. Now, the players list looks like this: Code: <ul id="players"> <li class="ui-state-default" style="list-style: none; margin-left: -40px; padding: 0px;"> <table width="700px" cellpadding="0" cellspacing="0" border="0"> <tr> <td style="width: 150px;"> <input type="text" style="width: 145px;"> </td> <td style="text-align: center; width: 35px;"> <input type="text" style="width: 20px;"> </td> <td style="text-align: center; width: 35px;"> <input type="text" style="width: 20px;"> </td> <td style="text-align: center; width: 35px;"> <input type="text" style="width: 20px;"> </td> <td style="text-align: center; width: 35px;"> <input type="text" style="width: 20px;"> </td> <td> <input type="text" style="width: 98%"> </td> </tr> </table> </li> </ul> The players list is comprised entirely of text boxes. How do I go about setting it up so that when I drop a player on the encounter list, it actually displays the players data that was dragged. 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. 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 Hi this is an assignment, ive been on it all night. I have done the bubble sort function and have to modify it. I work out that if i could stop the amount of times it loops it would make it more efficient. To do this is would need to stop the loop when no swaps have been made on the full array.lenght-1. i have tried using booleans, false and true on the amount of swaps using a while loop instead of my first for loop, however it only loops nine times...ie only covering the array once,hence does not swap the full array. so i tried leaving in the for loop that instructs it to loop for the full array. length. I have also tried using if... else at different positions within my function please i need some guidance, im going to pull my hair out i can see what need in my head just cant get it. Plus i am very very new to this My simple objective is.... to set a flag to stop the loop when there have not been any swaps for the duration of the array. length-1, hence the array is now organised and to display the amount of loops taken. Heres the part that ive been changing and my latest attempt which is using if, however it still loops for 90 loops. Code: var temp; ;// varible to hold temporay value, var numberOfLoops = 0 swap = true if (swap = true) { for (var count = 0; count < returnArray.length; count = count +1)// sets any array lenght to be used and the number of passes as lenght of array for (var i = 0; i < returnArray.length-1; i = i + 1)// starting postion and what elements should be covered minus one pass less than the arrray { if ((returnArray[i]) > (returnArray[i+1])) { temp = returnArray[i+1]; //hold second value in temp var returnArray[i+1] = returnArray[i];// replace value second value with first value returnArray[i] = temp;//replace first value with value held in temp var swap = true } else { swap = false } numberOfLoops = numberOfLoops + 1 } } window.alert('number of loops taken is ' + numberOfLoops) return returnArray My bubble sort function als0 worked fine showing 90 loops each time...until changed it 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. |