Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    New Coder
    Join Date
    Mar 2004
    Location
    UK
    Posts
    28
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Referencing array objects before/after sorting the array

    I am trying to order, and reference, an array of information such as scores, for example;

    Linda 7, David 5, Henry 10

    What I want to do is display the results in the right order by score. I can create an array called "scores" and sort it easily enough, but how do I "attach" the names to the scores so that these are listed in the right order, ie;

    Henry 10, Linda 7, David 5

    (I have seen sorting example scripts on the web, but all of these involve sorting a table - however, in reale life I am using a table of 100+ rows and 21 columns, with colour formatting to display the results, so the process of drawing table/sorting table/redrawing table is awfully long , I want to sort the data first, then just draw the table once. However I don't understand how to keep the names/scores tied together without using table row numbers.

    Any suggestions?
    BRUCE

  • #2
    Kor
    Kor is offline
    Red Devil Mod Kor's Avatar
    Join Date
    Apr 2003
    Location
    Bucharest, ROMANIA
    Posts
    8,478
    Thanks
    58
    Thanked 379 Times in 375 Posts
    use sort() - for normal sorting - than reverse() - to reverse the order methods

    See this
    PHP Code:
    <script>
    var 
    = new Array()
    s[0] = new Array('Mary',8);
    s[1] = new Array('John',5);
    s[2] = new Array('Paul',10);

    function 
    orderReverse(){
    s.sort();
    n.reverse();
    }
    </script> 
    Now you a new array, r whose elements are the same with the initial s but ordered inverse...
    KOR
    Offshore programming
    -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

  • #3
    New Coder
    Join Date
    Mar 2004
    Location
    UK
    Posts
    28
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks, this gets me 90% of the way there I beleve, but the 'sort' method uses an alphabetic sort as strings, whereas I need a numerical sort (e.g. by using the 'compareNumbers' method), but I can't see how to incorporate this into your approach. To give a more detailed idea of the kind of thing I need to achieve;

    <head>
    <script Language="Javascript1.2">
    //There are 3 teams, named for their owners. There are 3 points scoring rounds indexed [0] through to[2], and a total as index [3] (all have been calculated elsewhere, but I'll just put in the numbers in this example)

    var scores = new Array()
    scores["Mary"] = new Array(0,1,7,8)
    scores["John"] = new Array(10,11,12,33)
    scores["Paul"] = new Array(20,21,22,63)

    //Now create the array to be sorted according to Total score (I don't appear to be able to sort directly values of the above array, can't see why)
    var s = new Array()
    s[0] = new Array(scores["Mary"][3], scores["Mary"][0], scores["Mary"][1], scores["Mary"][2], 'Mary');
    s[1] = new Array(scores["John"][3], scores["John"][0], scores["John"][1], scores["John"][2], 'John');
    s[2] = new Array(scores["Paul"][3], scores["Paul"][0], scores["Paul"][1], scores["Paul"][2], 'Paul');

    //Next the function that does the business -
    function orderReverse(){
    n = s.sort();
    r = n.reverse();
    }
    </script>
    </head>

    <body>
    <script Language="Javascript1.2">
    //Run the sorting
    orderReverse()
    //Now display the highest value from the Total figures, & Owner name
    document.write("Total score = "r[0][0] + ", Owner name = " + r[0][4])

    </script>


    The problem is though, that 'sort' puts 8 as higher than 33 or 63!!!
    BRUCE

  • #4
    Regular Coder
    Join Date
    Jun 2002
    Location
    Round Rock, Texas
    Posts
    443
    Thanks
    0
    Thanked 0 Times in 0 Posts
    There is a really, really cool feature of the Array object sort function. Heres a reference: http://devedge.netscape.com/library/...y.html#1196882

    This looks really odd because you are passing a "compare function" in the sort parameter. YOU write the "compare function", and in this function you compare the elements you want. The reference above tells you what to return as the result of the compare.

    And just for grins, I wrote everything as objects.

    PHP Code:
    <html>
    <
    head>
    <
    script type='text/javascript'>
    function 
    Team (mynamemembers) {
       
    this.name myName;
       
    this.teamMates members;  // an array of players

       
    this.scoreSort = function (thisPlayerthatPlayer) {
           return 
    thisPlayer.score thatPlayer.score;
       }
    // end sortPlayers()


       
    this.nameSort = function(thisPlayerthatPlayer) {
          var 
    result Number.MAX_VALUE;

          switch (
    true) {
             case 
    thisPlayer.name == thatPlayer.name :
                
    result 0;
                 break;

             case 
    thisPlayer.name thatPlayer.name:
                
    result 1;
                break;

             case 
    thisPlayer.name thatPlayer.name:
                
    result = -1;
                break;
          }
          return 
    result;
       } 
    // nameSort()

       
    this.toString = function () {
          var 
    showTeam = new String();

          
    showTeam += "Team: " this.name +
                     
    "\nTeam Score: " this.totalScore();

          for (var 
    i=0i<this.teamMates.lengthi++) {
             
    showTeam += "\n" this.teamMates[i].name +
                                    
    "\t"  this.teamMates[i].score;
          }
          return 
    showTeam;
       }

       
    this.getPlayer = function (who) {
          var 
    thePlayer null;

          for (var 
    i=0i<this.teamMembers.lengthi++) {
             if (
    this.teamMembers[i].name == who) { // different CasEs will not match
                
    thePlayer this.teamMembers[i];
                break;
             }
          }
          return 
    thePlayer;
       } 
    // getPlayer()

       
    this.totalScore = function() {
          var 
    total 0;
          for (var 
    i=0i<this.teamMembers.lengthi++) {
             
    total += this.teamMembers[i].score;
          }
       return 
    total;
       } 
    // totalScore()
    // end Team object

    function Player (mynamemyscore) {
       
    this.name myname;
       
    this.score myscore;

       
    this.changeScore = function (theValue) {
          
    this.score += theValue;
       }
    }
    </script>
    </head>


    <body>

    </body>

    <script type='text/javascript'>
       var players = new Array();

       players[0] = new Player ('Mary', 5);
       players[1] = new Player ('John', 3);
       players[2] = new Player ('Sam', 8);
       var teamBob = new Team ('teamBob', players);

       alert ("Here is the team:\n" + teamBob); // toString() called by default

       teamBob.teamMembers.sort(teamBob.scoreSort);
       alert ("Here is the team sorted by score: \n" + teamBob);

       teamBob.teamMembers.sort(teamBob.nameSort);
       alert ("Here is the team sorted by name: \n" + teamBob.toString());
       
    </script>

    </html> 
    Last edited by RadarBob; 03-13-2004 at 05:47 AM.

  • #5
    New Coder
    Join Date
    Mar 2004
    Location
    UK
    Posts
    28
    Thanks
    0
    Thanked 0 Times in 0 Posts
    This is going to take me some time to work through/follow the logic here!
    BRUCE

  • #6
    New Coder
    Join Date
    Mar 2004
    Location
    UK
    Posts
    28
    Thanks
    0
    Thanked 0 Times in 0 Posts
    OK, RadarBob, I can follow the general approach, but I'm struggling on some of the key points, because I'm obviously WAY less fluent in JS than you are. I can run the script ( by the way I think you switched from teamMates to teamMembers, and myname to myName mid-code, in case you're trying to run it at your end ) and can see it works, but the method you use has a more complex way of referencing the array values than I was expecting. For instance, if I want to include individual values as well as the total in the array for each Player, for example;

    players[0] = new Player ('Mary', 10, 16, 26);
    players[1] = new Player ('John', 3, 14, 17);
    players[2] = new Player ('Sam', 8, 15, 23);

    I don't follow how I would change different elements of the script to cope with the ability to sort to either the "name" or the "Total" values, or for that matter any of the other values, other than the part of the Player function to;

    function Player (myName, myScore1, myScore2, myTotal) {
    this.name = myName;
    this.score1 = myScore1;
    this.score2 = myScore2;
    this.total = myTotal
    ...etc. ....


    If I could beg a working script on the above basis (), I should at least be able to follow what's changed from the original script you posted and the new one, which will help me to better understand the workings of individual bits of it.

    An example of the huge set of data I need to try and sort is at www.tggpc.co.uk/Results3.htm, page down to see the huge monster table.
    BRUCE

  • #7
    Regular Coder
    Join Date
    Jun 2002
    Location
    Round Rock, Texas
    Posts
    443
    Thanks
    0
    Thanked 0 Times in 0 Posts
    by the way I think you switched from teamMates to teamMembers, and myname to myName mid-code,
    Yeah, It was late at night and I was really watching an interesting TV show.

    .Explaining the sort
    but the methods you use has a more complex way of referencing the array values than I was expecting.
    Yes, it is odd. It was quite confusing to me when I first ran into this. I had a similar problem to solve and I ran into this Array.sort(functionName) thing that I'm trying to show here. I've found the best thing is to not think about it too much. Really. But this really, really solves the problem of sorting arrays of objects. And when you have mulit-dimentional or nested arrays like yours - well, that's exactly the same thing. You are having a problem because the "normal" way to use sort cannot actually get at / touch / see the data you actually are trying to sort on.

    Passing a function's name in the parameter list is odd. Just think of it as any other variable you'd normally pass.

    Then the actual compare function has two input parameters, but we did not pass in any parameters. What's going on? The best I can figure is that JS knows that this - teamMembers in this case - is an array, so it knows how do deal with it. So JS is telling me "just write the code like I tell ya, I'll worry about how it works."

    So what are these parameters? They are elements of the array! teamMembers is an array of Player objects. The parameters are Player objects. So now all you have to do in the compare function is reference the property (variable) that you want to compare and "tell the computer" what order to put things in....

    Returning 1 means "put a before b. Returning -1 means "put b before a". And finally one confusing point. The compare function clearly does not iterate through the array and compare all values. Well, again, JS knows what it's doing. Thus we can compare names, scores, whatever, and this funky mechanism allows us to sort on those things.

    Extending Existing Objects
    don't follow how I would change different elements of the script to cope with the ability to sort to either the "name" or the "Total" values, or for that matter any of the other values
    Ok, let's say you add "jersey number" to the Player and you want to sort on that.

    first, Add that property:
    Code:
    function_Player_(myname,_myscore, mynumber)_{ 
    ___this.name_=_myname; 
    ___this.score_=_myscore; 
       this.jersey = mynumber;
       . . .
    Now write a compare function. Note that it's basically a copy of the sortScores function.
    Code:
    function_Team_(myname,_members)_{ 
    ___this.name_=_myName; 
    ___this.teamMates_=_members;__// an array of players 
     
    ___this.scoreSort_=_function_(thisPlayer,_thatPlayer)_{ 
    _______return_thisPlayer.score_-_thatPlayer.score; 
    ___}// end sortPlayers() 
    
       this.jerseySort = function (thisPlayer, thatPlayer) {
          return thisPlayer.jersey - thatPlayer.jersey;
       }
    One final detail. We need to see the jersey number when we display the object.
    Code:
    this.toString_=_function_()_{ 
    ______var_showTeam_=_new_String(); 
     
    ______showTeam_+=_"Team: "_+_this.name_+ 
    _________________"\nTeam Score: "_+_this.totalScore(); 
     
    ______for_(var_i=0;_i<this.teamMates.length;_i++)_{ 
    _________showTeam_+=_"\n"_+_this.teamMates[i].name_+ 
    ______________________"\t"__+_this.teamMates[i].score;
                          "\t" + this.teamMates[i].jersey;
    ______} 
    ______return_showTeam; 
    ___}
    Now use it!
    Code:
    teamBob.teamMembers.sort(sortJersey);
    alert ("here's the team sorted by jersey number + teamBob.toString());
    Hardly 5 lines of JS added - and we have a new property, can view it, and sort on it. THIS is the power of object oriented programming.

    Object oriented think and your design
    if I want to include individual values as well as the total in the array for each Player, for example;

    players[0] = new Player ('Mary', 10, 16, 26);
    players[1] = new Player ('John', 3, 14, 17);
    players[2] = new Player ('Sam', 8, 15, 23);
    This code is going in the wrong direction I think. In the end, This code is going to be very difficult to use. What happens when you want only one score or now 4?

    As a first guess, you might replace the single score in the Player object with an array of scores. Then write functions to add a score, display the scores, etc. Now you have have as many or as few scores as needed. NOW, if you want to pass in scores at the time you create a new player, you pass in a array instead if individual scores. NOW the code is flexible.
    Code:
    function_Player_(myname,_myscores)_{ 
    ___this.name_=_myname; 
    ___this.scores_=_myscores;  // an array of scores 
     
       // OK, now we need functions to make use of the scores array
    ___this.totalScore = function() {
          var theTotal = 0;
    
          for (var i=0; i<this.scores.length; i++) {
             theTotal += this.scores[i];
          }
          return theTotal;
    ___} 
    }
    
    // and we need to modify the team total score code.
    // Note how small the change is. The Power of Object Oriented Programming again!
    function Team ( ...) {
       . . .
    
    __this.totalScore_=_function()_{ 
    ______var_total_=_0; 
    ______for_(var_i=0;_i<this.teamMembers.length;_i++)_{ 
    _________total_+=_this.teamMembers[i].totalScore();  // is this cool or what?!
    ______} 
    ___return_total; 
    ___}_// totalScore() 
    
    // and we must modify the sort routine
    this.scoreSort_=_function_(thisPlayer,_thatPlayer)_{ 
    _______return_thisPlayer.totalScore()_-_thatPlayer.totalScore();  // Wow! this stuff is easy!!
    ___}// end sortPlayers() 
    } 
    
    . . . 
    
    var skores = new Array();
    skores[0] = 4;
    skores[1] = 0;
    skores[3] = 8;
    skores[4] = 10;
    
    var me = new Player ('Bob', skores);
    I know what you're thinking, I'm making more work here. Yes there may be for typing to build the object's structures, but I guarantee you that overall this is a better approach.

    As for a total score for the player. That should always be calculated. If you keep it as a separate numeric variable then you will have to write much more code to make sure that value is always current. So instead just add up all the scores every time you want the total. Notice that this is how the Team object total score is done.

    Mind Blowers
    Given all the code with changes we've talked about here's some of the things we can do:
    Code:
    // how many players are on my team?
    alert ("Number of team members: " + teamBob.teamMembers.length);
    
    // What is the team's total score?
    alert ("team total score" + teamBob.totalScore());
    
    // What is Mary's total score?
    alert ("Mary's total score: " + teamBob.getPlayer('Mary').totalScore());
    
    // Who's on my team? give me their names, scores, and jersey number
    alert(teamBob.toString());
    
    // who is my worst player?
    teamBob.teamMembers.sort(sortScores);
    alert ("My best player is: + teamBob.teamMembers[0].name);
    
    // who is my best player?
    teamBob.teamMembers.sort(sortScores);
    alert ("My worst Player is: " + teamBob.teamMembers[teamBob.teamMembers.length - 1]);
    
    // tell me Sam's info:
    alert (teamBob.getPlayer('Sam'));
    
    // Joe just joined the team. Of course he doesn't have any scores yet. We'll give him jersey # 13
    // we should have written a function to do this inside the Team object
    var scores = new Array();
    teamBob.teamMember[teamBob.teamMembers.length] = new Player ('Joe', scores, 13);
    Improving the design
    After writing the examples above I see that sometimes we want to reference the end of the array of players. As written it looks convoluted. We could add a "number of players" property in the Team object. Referencing that would be shorter and more clear. It starts to come down to judgement as to how far you want to go with these things
    Code:
    Function Team (...) {
      . . .
       this.count = function () {
          return this.teamMembers.length;
       }
     . . .
    }// end of Team object
    
    // how many players are on my team?
    alert ("Number of team members: " + teamBob.count());
    
    // do something with every team member
    for (var i=0; i<teamBob.count(); i++) {
       // do stuff with teamBob.teamMembers[i]
    }

  • #8
    Regular Coder
    Join Date
    Jun 2002
    Location
    Round Rock, Texas
    Posts
    443
    Thanks
    0
    Thanked 0 Times in 0 Posts
    An example of the huge set of data I need to try and sort is at www.tggpc.co.uk/Results3.htm, page down to see the huge monster table.
    ALLL righty then! Let's have fun with this puppy!

    We're gonna build on the ideas from my last post...

    We have a Player object and we can sort those scores. We have a team, and we can sort the players by score. And we can easily get the team or player total scores.

    Looks like what we have here is a bunch of events.

    Code:
    function RaceEvent (eventName, theTeams) {
       this.name = eventName;
       this.teams = theTeams;  // array of teams
    
      // this code should look VERY FAMILIAR
      // remember we are sorting an array of team objects
       this.scoreSort = function (thisTeam, thatTeam) {
          var result = Number.MAX_VALUE;  // just to give it some initial value
    
          switch (true) {
             case thisTeam.totalScore() > thatTeam.totalScore() :
                result = 1;
                break;
    
             case thisTeam.totalScore() < thatTeam.totalScore() :
                result = -1;
                break;
    
             case thisTeam.totalScore() == thatTeam.totalScore():
                result = 0;
          } // switch
          return result;
       } // scoreSort()
    } // end of RaceEvent object
    
    //Ok how do we get here to use this. I'll build one of everything to demonstrate
    
    //scores for one player. reuse the array for other players
    var scores= new Array(0);
    scores[0] = 6;
    scores[1]= 10;
    
    // now the players
    var mates = new Array();
    mates[0] = new Player ('Bob', scores, 10) // don't forget the jersey number!
    
    //now the teams
    var theTeams = new Array();
    theTeams[0] = new Team('teamBob', mates);
    
    // now the event
    var LeMans = new RaceEvent ('LeMans', theTeams);
    
    //FINALLY, we can sort the whole enchelada
    
    LeMans.teams.sort(scoreSort);
    gee, this is getting easy
    Last edited by RadarBob; 03-13-2004 at 07:03 PM.

  • #9
    New to the CF scene
    Join Date
    Mar 2004
    Location
    Italy
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    A simple way

    In the meantime, I gave a look to your problem, Radar, and wrote down two lines just to spend one hour.........I took your data, and ordered the fields of total scores, then ordered the whole database according with the new order. The output is just to verify if it works. Try this very simple html page, if you agree..........

    <code>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <title>Ordinamento array Marco</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <LINK href="CSS_file\verdana.css" type=text/css rel=stylesheet>
    <script language="JavaScript1.1">
    function orderMarco(){

    var scores = new Array()
    scores["Mary"] = new Array(0,1,7,33)
    scores["John"] = new Array(10,11,12,3)
    scores["Paul"] = new Array(20,21,22,63)

    var s = new Array()
    s[0] = new Array(scores["Mary"][3], scores["Mary"][0], scores["Mary"][1], scores["Mary"][2], 'Mary');
    s[1] = new Array(scores["John"][3], scores["John"][0], scores["John"][1], scores["John"][2], 'John');
    s[2] = new Array(scores["Paul"][3], scores["Paul"][0], scores["Paul"][1], scores["Paul"][2], 'Paul');

    a=new Array(); //costruisco l'array dei punteggi totali
    for (i=0; i<3; i++){
    a[i]=s[i][0];
    }
    var q1, q2, temp; //lo ordino
    for (q1=0; q1<3; q1++) {
    for (q2=q1+1; q2<4; q2++) {

    if (a[q1]>a[q2]){

    temp=a[q1];
    a[q1]=a[q2];
    a[q2]=temp;
    }
    }
    }

    var j, k;
    sord=new Array(); //ricostruisco l'array di partenza nel nuovo ordine
    for (j=0; j<3; j++){
    for (k=0; k<3; k++){
    if (a[j]==s[k][0]){
    sord[j]=s[k];
    }

    }
    }
    document.write("<table><tr><td>"+s+"</td></tr>");
    document.write("<tr><td>"+a+"</td></tr>");
    document.write("<tr><td>"+sord+"</td></tr></table>");


    }
    </script>
    </head>
    <body>
    <center><h3>Ordinamento arrays con javascript</h3></center>
    <br/>
    <center><h4>Non badare all'impaginazione dei risultati....</h4></center>
    <br/>
    <br/>
    <a href="javascript: orderMarco();">Prova la funzione!</a>
    </body>
    </html>

    </code>

    but I think you should consider to manage the job with a database tool, f.i. Access with SQL could work fine.........

    Cheers

    Marco

  • #10
    New Coder
    Join Date
    Mar 2004
    Location
    UK
    Posts
    28
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Originally posted by RadarBob
    [B]Yeah, It was late at night and I was really watching an interesting TV show.[B]
    Yep, been, T-shirt etc., etc.


    You've obviously put a great deal of effort into trying to help me RadarBob , and so although I can see this is going to be even harder to digest than the first time around, I'll give it my best shot. I'm extremely grateful . My problem is I've learnt to get where I am (which in JS terms is to a fairly basic level ) through trial and error rather than building learning from fundamentals upwards, so understanding the theory behind this is not going to be easy.....


    On the set up of the scoring, it seems you're thinking there's a distinction between a team and it's players that I have to worry about here:- there are only teams and their scores that I need to be concerned with. Very briefly, a team is composed of 6 drivers chosen by the owner at the start of the season, and the points the team scores at each of the 18 races are based on what happens with those 6 drivers at each race. Whilst I have quite a bit of JS code to calculate drivers results, in the big results table I'm trying to produce here, I only need to worry about team names, team scores at the individual races, and each team's total score for the season so far, I don't need to worry about driver scores - whilst the JS for calculating these probably isn't remotely close to the most efficient way of doing it , I don't want to make changes to it, because a) it works, and b) I wrote it from scratch as I learnt and therefore understand it intimately if tweaks are needed. If I don't understand it fully (which it seems I'm at risk of in respect of this results table), if I need to make changes I'm up sh*t creek with no paddle. For that reason (and with no offence meant to yourself in any way), if I don't understand it, I won't be willing to use it.

    So, I'm about to go into a darkened room and read your posts until my forehead bleeds.....
    BRUCE

  • #11
    Regular Coder
    Join Date
    Jun 2002
    Location
    Round Rock, Texas
    Posts
    443
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I think I understood the Italian more than the array construction.

  • #12
    New to the CF scene
    Join Date
    Mar 2004
    Location
    Italy
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    meant bherrington.........

    but regards to both, it's a very good and useful forum, mostly for a newbie like I am........will try to join you more often.

    See you

    Marco

  • #13
    New Coder
    Join Date
    Mar 2004
    Location
    UK
    Posts
    28
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: A simple way

    costruisco l'array dei punteggi totali
    ricostruisco l'array di partenza nel nuovo ordine
    Ordinamento arrays con javascript
    Non badare all'impaginazione dei risultati....
    ....etc...

    Marco, you obviously speak fluently at least 1 language more than I do . Sorry, but you lost me - I see the page displaying something, but I've no idea what it says or how it manages to say it .

    Re SQL database, I'm operating on a shoestring budget, and whilst I know this would be a better way of handling it, I'm stuck with JS arrays. I only started the website 4 years ago as a favour for a friend who started running this fantasy racing competition (with 12 teams in the first year - Ha!, the good old days), and I did it because I wanted to learn a little about websites and HTML(!!!). I started hand typing in HTML the results after each race! Back then the idea of even learning Javascript was as far away for me as becoming a brain surgeon. My friend has the luxury of running his competition records on spreadsheets via MS Excel, but I can't translate that easily to the web using an old version of FrontPage & a text editor, dirt cheap domain hosting and forwarding to a cheap/no frills ISP.
    BRUCE

  • #14
    Regular Coder
    Join Date
    Jun 2002
    Location
    Round Rock, Texas
    Posts
    443
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Whilst I have quite a bit of JS code to calculate drivers results, in the big results table I'm trying to produce here, I only need to worry about team names, team scores at the individual races, and each team's total score for the season so far, I don't need to worry about driver scores -
    I see. Overkill on my part way down at the Player level. And I take it the "data orientation" is "teams have events" rather than "events have teams". Let's redesign:
    Code:
    function Team (teamname, teamtotal) {
       this.name = teamname;
       this.totalScore = teamtotal;  // season total score
    } // end of Team object
    
    
    function sortScore (thisTeam, thatTeam) {
          return thisTeam.totalScore - thatTeam.totalScore;
    }
    
    // build an array of teams and sort it
    var theTeams = new Array();
    theTeams[0] = new Team ('Cofidis', 200);
    theTeams[1] = new Team ('USPS', 800);
    theTeams[1] = new Team ('Festiva', 120);
    
    theTeams.sort(sortScore);
    Last edited by RadarBob; 03-13-2004 at 07:39 PM.

  • #15
    New to the CF scene
    Join Date
    Mar 2004
    Location
    Italy
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    to clarify...

    Sorry for having been away, dinnertime here

    Well, I was trying a very simple solution only for this particular circumstance, even if a general (and so nice) approach like Radar's is anyway preferable.........

    In the first line of the output table you can see your unordered data.

    In the second one the total scores have been ordered.

    In the third line, the complete data are re-ordered showing the team with the lowest total score at the first place, and so on........sorry for not givind a decent look to the output, I preferred to work on some Javascript than on HTML tables today

    I built a new array with the total scores values:

    <code>
    a=new Array(); for (i=0; i<3; i++){
    a[i]=s[i][0];
    }
    </code>

    then ordered it:

    <code>
    var q1, q2, temp; //lo ordino
    for (q1=0; q1<3; q1++) {
    for (q2=q1+1; q2<4; q2++) {
    if (a[q1]>a[q2]){
    temp=a[q1];
    a[q1]=a[q2];
    a[q2]=temp;
    }
    }
    }
    </code>

    and finally re-ordered the original data in the same order as their total scores fields:

    <code>
    var j, k;
    sord=new Array();
    for (j=0; j<3; j++){
    for (k=0; k<3; k++){
    if (a[j]==s[k][0]){
    sord[j]=s[k];
    }
    }
    }
    </code>

    The rest is all to show the output..........I just took the opportunity you offered me to study a few.
    What we are missing, is to manage the case in which 2 value of total score are equal.........but it must not be hard.

    Ok, have a good time then, bye

    Marco


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •