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.
Results 1 to 8 of 8
  1. #1
    New to the CF scene
    Join Date
    Jan 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Need Help with Sorting

    Hi everyone,

    I'm new to the forums. I have been coding some simple javascript but it is really new to me. I coded a segment that you can see below but the part in bold doesn't work. I need it to sort by count descending. I'm having major issues with it. Thanks for the help ahead of time

    Code:
    <html>
      
    <head>
        
    <title>ENGO Lab 2.1</title>
      
    
    
    
    <script type="text/javascript">
    
    
    var d=new Date();
    
    var weekday=new Array(7);
    
    weekday[0]="Sunday";
    
    weekday[1]="Monday";
    
    weekday[2]="Tuesday";
    
    weekday[3]="Wednesday";
    
    weekday[4]="Thursday";
    
    weekday[5]="Friday";
    
    weekday[6]="Saturday";
    
    
    
    var month=new Array(12);
    
    month[0]="January";
    
    month[1]="February";
    
    month[2]="March";
    
    month[3]="April";
    
    month[4]="May";
    
    month[5]="June";
    
    month[6]="July";
    
    month[7]="August";
    
    month[8]="September";
    
    month[9]="October";
    
    month[10]="November";
    
    month[11]="December";
    
    
    
    document.write("Today is " + weekday[d.getDay()] + "<br />" + d.getFullYear() + "/" + month[d.getMonth()] + "/" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds());
    
    
    
    
    </script>
    
    
    <script type="text/javascript">
    
    
    function sort_descending_count(w){
    
    var sorted = w.sort();
    sorted.reverse();
    var stuff;
    
    var wordCounts = {};
    
    var wordHold = {};
      
    for(i=0; i < w.length; i ++ ){
        
    stuff = sorted[i];
      	  
    
    if( wordCounts[stuff] == null ){
          
    wordCounts[stuff] = 1;
      
    wordHold[stuff] =  stuff;
    }
    
    else{
          
    wordCounts[stuff] += 1;
      
    }
     
    
    
    } 
     
    
    var i = 1;
    
    wordCounts.sort();
    
    var i = 1;
    
    var str = '<table border="1" cellspacing="1" cellpadding="5"><th>Sequence</th><th>Word</th><th>Count</th>';
    
    
    for( stuff in wordCounts){
    
    
    
    str+='<tr><td>'+i+'</td><td>'+stuff+'</td><td>'+wordCounts[stuff]+'</td></tr>';
    
    
    i = i+1;
    }
    
    str+='</table>';
    
    
    
    document.getElementById('change2').innerHTML = txt;
    
    
    
    
    }
    
    </script>
    
    
    
    
    <script type="text/javascript">
    
    
    function sort_descending(w){
    
    var sorted = w.sort();
    sorted.reverse();
    var stuff;
    
    var wordCounts = {};
      
    for(i=0; i < w.length; i ++ ){
        
    stuff = sorted[i];
      	  
    if( wordCounts[stuff] == null ){
          
    wordCounts[stuff] = 1;
        
    }
    
    else{
          
    wordCounts[stuff] += 1;
        
    }
     
    
    
    } 
     
    
    var i = 1;
    
    var str = '<table border="1" cellspacing="1" cellpadding="5"><th>Sequence</th><th>Word</th><th>Count</th>';
    
    
    for( stuff in wordCounts){
    
    
    
    str+='<tr><td>'+i+'</td><td>'+stuff+'</td><td>'+wordCounts[stuff]+'</td></tr>';
    
    
    i = i+1;
    }
    
    str+='</table>';
    
    
    
    document.getElementById('change2').innerHTML = str;
    
    
    
    
    }
    
    </script>
    
    
    
    
    <script type="text/javascript">
    
    
    
    var words;
    function show_prompt()
    {
    
    var name=prompt("Please input a list of words seperated by a space","Banana Apple Orange");
    
    if (name!=null && name!="")
      
    {
      
      
    // split input into array using space
      
    var arrayOfWords = name.split(" ");
    
    
      // construct object to save each word and its count
      
    var wordCounts = {};
      
    words = arrayOfWords;
    for(i=0; i < arrayOfWords.length; i ++ ){
        
    var w = arrayOfWords[i];
      	  
    if( wordCounts[w] == null ){
          
    wordCounts[w] = 1;
        
    }
    
    else{
          
    wordCounts[w] += 1;
        
    }
     
    
    
    } 
     
      
    
    
    
    // output the result
    
    
    
    var str = '<table border="1" cellspacing="1" cellpadding="5"><th>Word</th><th>Count</th>';
    
    
    for( w in wordCounts){
    
    str+='<tr><td>'+w+'</td><td>'+wordCounts[w]+'</td></tr>';
    
    
    }
    
    str+='</table>';
    
    
    
    document.getElementById('change').innerHTML = str;
    
    
    
    
    var button = '<input type="button" onclick="sort_descending(words)" value="Sort with word alphabetically descending">';
    var button2 = '<input type="button" onclick="sort_descending_count(words)" value="Sort with word count descending">';
    
    document.getElementById('sorting').innerHTML = button;
    document.getElementById('sorting2').innerHTML = button2;
    
    }
    
    
    
    else 
    	
    {
    
    		
    alert("The Input is Not Valid");	
    
    	
    }
    
    
    
    
    }
    
    window.onload=show_prompt;
    
    
    
    </script>
    
    
    
    </head>
    
    
    <body>
    
    
    
    <br />
    
    
    <div id="change">
    </div>
    
    
    
    <div id="sorting">
    </div>
    
    <div id="sorting2">
    </div>
    
    
    
    <div id="change2">
    </div>
    
    
    
    
    
    </body>
    
    </html>]
    Last edited by LiMeh; 01-23-2012 at 09:10 AM.

  • #2
    New to the CF scene
    Join Date
    Jan 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Bump Bump

  • #3
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    The JavaScript Array.sort() method sorts alphabetically unless you override the comparison function. So 10 comes before 2. because the first character gets compared before seeing if there is a second with the default comparison.

    To sort into descending order numerically you could replace:

    Code:
    var sorted = w.sort();
    sorted.reverse();
    with

    Code:
    numD = function(a, b){return (b-a);};
    var sorted = w.sort(numD);
    because that now sorts into descending numeric order there is no need to reverse the order afterwards.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #4
    New to the CF scene
    Join Date
    Jan 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by felgall View Post
    The JavaScript Array.sort() method sorts alphabetically unless you override the comparison function. So 10 comes before 2. because the first character gets compared before seeing if there is a second with the default comparison.

    To sort into descending order numerically you could replace:

    Code:
    var sorted = w.sort();
    sorted.reverse();
    with

    Code:
    numD = function(a, b){return (b-a);};
    var sorted = w.sort(numD);
    because that now sorts into descending numeric order there is no need to reverse the order afterwards.
    Hi Felgall,

    Sorry if I posed the wrong question initially.
    I was able to get the descending sort to work with the alphabetical series and numerical.

    My issue right now is that I am trying to sort the "count" rather then the words. I don't know how to change my loop so that I display the words as a function of the count rather then the other way if you understand what I'm trying to get at.

    For example.

    I can sort like this right now:

    Word Count
    Orange 1
    Banana 4
    APple 2

    I want to be able to sort like this now:

    Word COunt
    Banana 4
    Apple 2
    Orange 1

  • #5
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    If the number part is always after the first space then you can use:

    Code:
    numD = function(a, b){c = a.split(/\s/); d = b.split(/\s/);  return (d[1]-c[1]);};
    var sorted = w.sort(numD);
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    Ummm...Felgall: He doesn't actually *have* an array.

    There's not "number part after the space."

    What he actually has is (JSON notation):
    Code:
    wordcounts = {
        "Orange" :  1,
        "Banana" :  4,
        "Apple" :  2
    };
    and *that* is what he wants to sort. By the value part of each key/value pair.
    Last edited by Old Pedant; 01-24-2012 at 02:46 AM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    Quite frankly, I don't know how to do this except by converting the wordcounts object into an array.

    Do you?

    This is the best I can come up with:
    Code:
    <script>
    wordcounts = {
        "Orange" : 1,
        "Banana" : 4,
        "Apple" : 2
    };
    
    function word( w, c )
    {
        this.name = w;
        this.count = c;
    }
    
    var words = [];
    for ( w in wordcounts )
    {
        words.push( new word(w, wordcounts[w]) );
    }
    
    var sorted = words.sort( function( a, b ) { return a.count - b.count; } );
    for ( s = 0; s < sorted.length; ++s )
    {
        document.write( sorted[s].count + "::" + sorted[s].name + "<br/>");
    }
    </script>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    His array of words is just something like
    Code:
    words = [
        "Banana",
        "Orange",
        "Banana",
        "Apple",
        "Banana",
        "Apple",
        "Banana"
    ];
    So, sure, he can sort that. But he has no way of matching the counts with the sorted words.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

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