JavaScript - Sort Is Not A Function Error When Ordering An Array Of Integers
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! Similar TutorialsOkay so im just doing a little test and this might seem like a really stupid question but i cant figure it out...all i simply want to do is take all those numbers and get the sum then display the sum in a document.write in theory i should get 10 but i dont and idk why i have tried many many things Code: var numbers = new Array(); numbers[0] = 1; numbers[1] = 2; numbers[2] = 3; numbers[3] = 4; thanks Hi all, I have an array holding 100 randomly generated integers between 0-9 inclusive...firstArray[99] how do i use a second array to keep count of how many times each integer is generated..secondArray[9] I'm trying to pass titleArray and pointsArray to the task(); I'm getting an error mgs this.assignments() is not a function. I've highlighted this.assignments() Code: <html> <head> <title>Variable - Examples 1</title> <script type="text/javascript"> function Student(firstName, lastName, email, courseID, titleArray, pointsArray){ this.firstName = firstName; this.lastName = lastName; this.email = email; this.courseID = courseID; this.title = titleArray; this.points = pointsArray; this.assignments = task; this.totalPoints = addExam; this.finalGrade = calcGrade; } Student.prototype = { constructor : Student, toString : studentInfo }; var t = this.title; var p = this.points; function task(t, p){ var title = this.t; var points = this.p; var titlePoints = ""; for (var i=0; i < points.length; i++){ titlePoints += title[i] + " : " + points[i] + "<br>"; } return titlePoints; } function addExam(){ var assignments = [30, 30, 28, 27, 29]; var exams = [41,45]; var highOfTwo = Math.max(41,45); var sum = 0; for (var i=0; i < assignments.length; i++){ sum += assignments[i]; } return sum + highOfTwo; } var totalPoints = addExam(); function calcGrade(){ var grade; if (totalPoints >= 190){ return "A+"; }else if (totalPoints >= 180){ return "A"; }else if (totalPoints >= 175){ return "B+" }else if (totalPoints >= 170){ return "B"; }else if (totalPoints >= 165){ return "B-"; }else if (totalPoints >= 160){ return "C"; }else if (totalPoints >= 150){ return "D"; }else if (totalPoints < 150){ return "F"; } } function studentInfo(){ return "Student : " + this.lastName + "," + this.firstName + "<br>"+ "eMail : " + this.email + "<br>" + "Course ID : " + this.courseID + "<br>" + "--------------------------------" + "<br>" + this.assignments() + "--------------------------------" + "<br>" + "Total Points : " + this.totalPoints() + "<br>" + "Final Grade : " + this.finalGrade(); } var titleArray = ["Assignment1","Assignment2","Assignment3","Assignment4","Assignment5","MidTerm", "Final"]; var pointsArray = [30, 30, 28, 27, 29, 41, 45]; var student = new Student("FirstName", "Lastname", "myemail@gmail.com","COIN-070B.01", titleArray, pointsArray ); </script> </head> <body> <script type="text/javascript"> document.writeln(student.toString()); </script> </body> </html> 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 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 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, 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. 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. i keep getting error Call to undefined function codeandurl() below is my code PHP Code: <?php $value= strip_tags(get_field('link',$post)); $resultid=get_field('resultid',$post); codeandurl($resultid,$value); ?> <div id="result"></div> <script type="text/javascript"> function codeandurl(resultid,url){ $( "#result" ).text(resultid); $( "#result" ).dialog({ modal: true, buttons: { Ok: function() { $( this ).dialog( "close" ); } } }); window.open(url); return false; } </script> 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]); I'm trying to "progressively enhance" one of my surveys using javascript. Basically, I have rating scales that make use of radio buttons as each point on the scale. Each radio button occupies its own cell in a table. I wrote some functions that will highlight cells on mouseover in a color corresponding to its position on the scale (e.g. the lowest point is red, the midpoint is yellow, the highest point is green). When a radio button is clicked, the background of the button's cell and preceding cells in the same row will be colored accordingly. The functions are working well in FireFox and Chrome (I just have to add a few lines using the addEvent function to make it compatible with IE). The effect looks a lot nicer when I add a function that makes the visibility of the radio buttons hidden. However, I want to make sure that there is a fallback option in case the functions that color the cells don't work for whatever reason. I would not want the radio buttons hidden in this case. Is there a method whereby I can call the "hideRadiobuttons" function only if the other functions are successfully executed? Write a program named Median.java that asks the user for three integers and outputs the median. I have to do this using if else statements. It seems really easy, but I can't figure it out. Help! Here's my code: Code: import java.util.*; public class Median { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.println("Please enter number 1"); int max = console.nextInt(); int min = max; int median = min; for (int i=2; i <= 3; i++) { System.out.println("Please enter number "+i); int enteredNumber = console.nextInt(); if (enteredNumber > max) { max = enteredNumber; } else { enteredNumber = median; } if (enteredNumber < min) { min = enteredNumber; } else { enteredNumber = median; } } System.out.println("The median is: "+median); } } When I run this it just gives me back the first number I entered. Can you guys please tell me why the link() function isnt working. Code: <html> <head> <script type ="text/JavaScript"> var counter = 0; var counter2 = 0; var arraynumb = 0; var arraynumb2 = 0; var global; var array = ['Mohamad', 'Karim', 'Anthony', 'Rami', 'Natalia', 'Sarah', 'Samer', 'Violette', 'Plume', 'Sharshabil']; var array2 = ["1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009"]; var searchKey = document.searchform.inputVal.value; var searchKey2 = document.searchform.inputVal2.value; var searchKey3 = document.searchform.inputVal.value; function pass(){ searchKey = document.searchform.inputVal.value; for (var i = 0, len = array.length; i < len; i++){ if (array[i] == searchKey){ counter = 1; arraynumb = i; } } } function pass1(){ searchKey2 = document.searchform.inputVal2.value; for (var i = 0, len = array2.length; i < len; i++){ if (array2[i] == searchKey2){ counter2 = 1; arraynumb2 = i; } } } function access() { if (counter == 1 && counter2 == 1 && arraynumb == arraynumb2) { window.alert("You may access the website"); window.alert(array[0]); global = 1; } else{ window.alert("You may not access the website"); global = 0; } } function link() { if (global == 1 && array[0] == searchkey3 ) { window.alert("You are an administrator, you may use all the ciphers"); } else window.alert("you are not signed in, please do so"); } </script> </head> <body> <form name = "searchform" action = ""> <p>Enter username<br/> <input name = "inputVal" type = "text" size = "30"/> <input name = "search2" type = "button" value = "Search" onclick = "pass()"/> </p> <p>Enter password<br/> <input name = "inputVal2" type = "password" size = "30"/> <input name = "search" type = "button" value = "Search" onclick = "pass1()"/> <input name = "Access site" type = "button" value = "Access" onclick = "access()"/> <br/> <br/> <input name = "linkto" type = "button" value = "Shift" onclick = "link();"/> <br/> </p> <br/> <p></p> </form> </body> </html> Code: <html> <head> <script> function changeBgColor(){ document.getElementById("bgc").style.background-color=333333; } </script> <style> #bgc{ width:300px; height:100px; background-color:#cccccc; } </style> </head> <body> <p id="bgc" onmouseover="changeBgColor()"> Hi There, pls change bg color </p> </body> </html> I am getting following error "SCRIPT5007: The value of the property 'changeBgColor' is null or undefined, not a Function object eventTest1.html, line 22 character 29" This is a simple code, why am I getting such a weird error. Whats wrong in here ? Thanks For some reason in IE this script Code: <script type="text/javascript"> //<![CDATA[ function SelectDisplayDiv(pointer){var divs = document.getElementsByClassName('hiddenDiv');for(var i =0; i < divs.length; ++i){divs[i].style.display = "none";} document.getElementById(pointer).style.display = 'block';}//]]> </script> is saying "Object doesn't support this method or property" But this script Code: function SelectDisplayDiv(pointer){var divs = document.getElementsByClassName('hiddenDiv');for(var i =0; i < divs.length; ++i){divs[i].style.display = "none";} document.getElementById(pointer).style.display = 'block';} *almost the exact same thing, just not written to the canvas by code, hard coded rather- does not. What does that error mean? Is this an IE thing? Hi, The Problem I get a error message only in IE when ever I try to call a function from an external file. I am using jQuery if that makes any difference and various plugins. Quote: Error: The value of the property '<function name>' is null or undefined, not a Function object. All the call work fine in FF, chrome, safari etc but for some reason I just can't get it to work with IE. This is getting annoying now, i have no idea what is causing it. here is an example: admin.js Code: function create_cleditor_admin_form(textarea_object) { $(textarea_object).cleditor({ height: 120, controls: // controls to add to the toolbar "bold italic underline | color highlight removeformat | bullets numbering | alignleft center alignright justify | undo redo | ", useCSS: false }); } calling code Code: $(document).ready(function() { try { create_cleditor_admin_form('textarea'); } catch(e) { alert("Error: "+e.message); } }); I have tried searching for this error on google and came up empty handed, surely it just something very stupid. Thanks in advance My isNumber function below gives 'event is not defined' error when I press the home key or the tab key - how can I fix that? Thanks PHP Code: function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode // 86 == ctrl-v // 36 == shift home to select entire field // 46 delete // 35 end // 36 home // 67 ctrl-c // 40 down key //alert(charCode); if ( (charCode == 35 || charCode == 40 || charCode == 86 || charCode == 46 || charCode == 67 || charCode == 36 || charCode == 8 || charCode == 9 || charCode == 32) || (charCode >= 48 && charCode <= 57) ) { return true; } return false; hi guys, im not very good with javascript/jquery, i have the following code: Code: <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $(window).ready(function() { $("#responsecontainer").load("includes/inc-mess-jail.php", function(response, status, xhr) { }); var refreshId = setInterval(function() { $("#responsecontainer").load('includes/inc-mess-jail.php?randval='+ Math.random()); }, 9000); $.ajaxSetup({ cache: false }); }); </script> it basically updates the div tag: Code: <tr> <td colspan="2"> <div id="responsecontainer" align="center"></div> </td> </tr> i wanted to add an error message to it, that comes up underneath the <div id="responsecontainer" align="center"></div> that says "Error" with an id number next to it, then when your mouse goes over it a box comes out saying "there was a problem retrieving your information. the game will continue trying to resolve this" and then underneath where it says error i would like it to say the number of attempts it has tried to recollect the information. obviously i would only like this error message to come up, when it cannot refresh the information. Any help would be great, even pointing me in the right direction why does my javascript function run right away when the page loads? but not wen the button is clicked? its working the opposite to how i want it to i didnt include the other html tags to help focus on this. Btw im tryna avoid the method of having the onclick="funct()" method which would be written in the button tag. Thank you. <body> <button id="mybutton">Click me</button> </body> <script type = "text/javascript"> var b = document.getElementById("mybutton"); b.onclick = funct() function funct() { alert("Thanks for clicking me!"); } </script> |