www.webdeveloper.com
Results 1 to 8 of 8

Thread: sorting a two-dimensional array

Hybrid View

  1. #1
    Join Date
    May 2009
    Posts
    40

    Question sorting a two-dimensional array

    Hello everyone,
    I'm trying to sort a two-dimensional array by it's second[1] and third[2] position.
    I managed to sort it by it's first[0] position with the simple sort() function, but I can't seem to find any working solution to what I want.
    I've added my code and the final output I'm trying to achieve:
    printArr() and sortByName() works great! I need help with the sortByPhone() and sortByEmail() ones.

    Code:
    <script type="text/javascript">
                var studentArr = new Array();
                studentArr[0] = new Array("Lior Iluz", "03-7262123", "lior@domain.com");
                studentArr[1] = new Array("David Abutbul", "08-5232424", "david@domain.com");
                studentArr[2] = new Array("Lior Bourla", "04-6232424", "lior@domain.com");
                studentArr[3] = new Array("Adi Efrati", "08-9232427", "adi@domain.com");
                studentArr[4] = new Array("Yossi Morad", "04-4232427", "yossi@domain.com");
                studentArr[5] = new Array("Avishai Davis", "03-6232427", "avishai@domain.com");
                studentArr[5] = new Array("Petra Russo", "04-7232427", "petra@domain.com");
                
                function printArr(){
                    document.getElementById('table').innerHTML = '<h2>Students List</h2';
                    document.getElementById('table').innerHTML += '<p><span class="col1"><font color="#265e16"><strong>#</strong></font></span></span><span class="col2"><a href="index.html" title="Sort By Name" onclick="sortByName();return false;">Name</a></span><span class="col3"><a href="#" onlick="sortByPhone();return false;">Phone</a></span><span class="col4"><a href="#" onlick="sortByEmail();return false;">Email</a></span></p><div class="cleaner"></div>';
                    for (var i = 0; i < studentArr.length; i++) {
                        document.getElementById('table').innerHTML += '<p><span class="col1">' + i + '</span><span class="col2">' + studentArr[i][0] + '</span><span class="col3">' + studentArr[i][1] + '</span><span class="col4">' + studentArr[i][2] + '</span></p><div class="cleaner"></div>';
                    }
                }
    //a working simple sort - sorts by the first[0] position
    function sortByName(){
                    studentArr.sort();
                    printArr();
                }
    //a tryout with a script I've found while searching all over google ;)
    function numberSort(a,b){
                    return ((a[1] < b[1]) ? -1 : ((a[1] > b[1]) ? 1 : 0));
                }
                
                function sortByPhone(){
                    studentArr.sort(numberSort());
                    printArr();
                }
    //same as sortByPhone() but I thought maybe it'll work on this one :\
    function sortByEmail(){
                    studentArr.sort(numberSort());
                    printArr();
                }
      </script>
    the output I want is:
    Code:
    sortByPhone();
    03-7262123
    04-4232427
    04-6232424
    04-7232427
    08-5232424
    08-9232427
    and:
    Code:
    sortByEmail(); - //I know when I use sortByName it also sort the emails but that's only because I used emails with the same names as the user name itself... (fake emails...)
    adi@domain.com
    david@domain.com
    lior@domain.com
    lior@domain.com
    petra@domain.com
    yossi@domain.com
    Thank you very much!

  2. #2
    Join Date
    Nov 2002
    Location
    Baltimore, Maryland
    Posts
    12,279
    Code:
    studentArr.sort(numberSort());
    That calls the function numberSort and then srots the array using the function returned, but no function is returned. Instead you want
    Code:
    studentArr.sort(numberSort);
    “The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect.”
    —Tim Berners-Lee, W3C Director and inventor of the World Wide Web

  3. #3
    Join Date
    May 2009
    Posts
    40
    Charles, I deleted the spare () and now something happens but not the right result... it just sorts it out with no recognized order... something wrong with the numberSort() function?
    Last edited by liorry; 05-29-2009 at 10:30 AM.

  4. #4
    Join Date
    Nov 2002
    Location
    Baltimore, Maryland
    Posts
    12,279
    Other than that I'm not sure just what you are doing wrong, but here's a woking example:
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    	<head>
    		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    		<title>Example</title>
    	</head>
    	<body>
    	<ul>
    	<script type="text/javascript">	
    <!--
        var studentArr = new Array();
        studentArr[0] = new Array("Lior Iluz", "03-7262123", "lior@domain.com");
        studentArr[1] = new Array("David Abutbul", "08-5232424", "david@domain.com");
        studentArr[2] = new Array("Lior Bourla", "04-6232424", "lior@domain.com");
        studentArr[3] = new Array("Adi Efrati", "08-9232427", "adi@domain.com");
        studentArr[4] = new Array("Yossi Morad", "04-4232427", "yossi@domain.com");
        studentArr[5] = new Array("Avishai Davis", "03-6232427", "avishai@domain.com");
        studentArr[5] = new Array("Petra Russo", "04-7232427", "petra@domain.com");
        
        function byName (a, b) {return a[0] == b[0] ? 0 : a[0] < b[0] ? -1 : 1}
        function byNumber (a, b) {return a[1] == b[1] ? 0 : a[1] < b[1] ? -1 : 1}
        function byAddress (a, b) {return a[2] == b[2] ? 0 : a[2] < b[2] ? -1 : 1}
        
        
        studentArr.sort(byAddress);
        
        for (i = 0; i < studentArr.length; i++) document.write ('<li>', studentArr[i], '<\/li>');
    // -->
    	</script>
    	</ul>
    	</body>
    </html>
    “The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect.”
    —Tim Berners-Lee, W3C Director and inventor of the World Wide Web

  5. #5
    Join Date
    May 2009
    Posts
    40
    Weird thing... if I use your code alone it works like a charm... but if I only use your functions and call them to fit my code - it doesn't work good (changes the order but not in the right way).
    I'll check what causes that in my code...

    Thank you very much for your time and help!

    Solved

  6. #6
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,434

    Arrow Alternative versions

    Here's another version [2 in fact], but Charles thinks and types faster than me :
    Code:
    <html>
    <head>
    <title>Sub-Sorts</title>
    <script type="text/javascript">
    // From: http://www.webdeveloper.com/forum/showthread.php?t=210008
    
    var studentArr = new Array();  // Note: changed contents of array for demonstration purposes only
        studentArr[0] = new Array("Iluz, Lior", "03-7262123", "lior1@domain.com");
        studentArr[1] = new Array("Abutbul, David", "08-5232424", "david@domain.com");
        studentArr[2] = new Array("Bourla, Lior", "04-6232424", "lior2@domain.com");
        studentArr[3] = new Array("Efrati, Adi", "08-9232427", "adi@domain.com");
        studentArr[4] = new Array("Morad, Yossi", "04-4232427", "yossi@domain.com");
        studentArr[5] = new Array("Davis, Avishai", "03-6232427", "avishai@domain.com");
        studentArr[5] = new Array("Russo, Petra", "04-7232427", "petra@domain.com");
    var tempArr = new Array();
                
    function printArr(){
      var str = '<h2>Students List</h2>';
          str += '<table border="1"><tr>';
    
    // version 1
          str += '<th>#</th>';
          str += '<th><span class="col2"><a href="#" onclick="sortBy(0);return false;">Name</a></span></th>';
          str += '<th><span class="col3"><a href="#" onclick="sortBy(1);return false;">Phone</a></span></th>';
          str += '<th><span class="col4"><a href="#" onclick="sortBy(2);return false;">Email</a></span></th>';
          str += '</tr>';
    //      str += '<div class="cleaner"></div>';
    
    // version 2
    //  str += '<th>#</th><th>Name</th><th>Phone</th><th>Email</th></tr>';
    
    // common for both versions 1 & 2
      for (var i = 0; i < tempArr.length; i++) {
         ptr = tempArr[i].split('|');
         j = ptr[1];
         str += '<tr>';
         str += '<td><span class="col1">' + i + '</span></td>';
         str += '<td><span class="col2">' + studentArr[j][0] + '</span></td>';
         str += '<td><span class="col3">' + studentArr[j][1] + '</span></td>';
         str += '<td><span class="col4">' + studentArr[j][2] + '</span></td>';
         str += '</tr>';
    //     str += '<div class="cleaner"></div>';
      }
      str += '</table>';
      document.getElementById('table').innerHTML = str;
    }
    
    function sortBy(field){
      tempArr = []; 
      for (var i=0; i<studentArr.length; i++) { tempArr.push(studentArr[i][field]+'|'+i); }
      tempArr.sort();
      printArr();
    }
    </script>
    </head>
    <!-- body -->            <!-- use with version 2, if desired -->
    <body onload="sortBy(0)"><!-- use with version 1 -->
    
    <!-- Use next section with version 2, if desired
    Sort by: 
    <button onClick="sortBy(0)">Name</button>
    <button onClick="sortBy(1)">Phone</button>
    <button onClick="sortBy(2)">Email</button>
    -->
    <div id="table"></div>
    </body>
    </html>

  7. #7
    Join Date
    May 2009
    Posts
    40
    @JMRKER
    haha he did answered fast
    thank you for your 2 examples! I'll use them to learn a couple of things

  8. #8
    Join Date
    May 2009
    Posts
    40
    I've found what was wrong - the syntax in my links. for some reason these didn't work (although it worked with a simple Arr.sort(); function)
    Code:
    <a href="#" onlick="sortByPhone();return false;">Phone</a>
    <a href="#" onlick="sortByEmail();return false;">Email</a>
    while these ones did work!
    Code:
    <a href="javascript:sortByPhone();" title="Sort By Phone">Phone</a>
    <a href="javascript:sortByEmail();" title="Sort By Email">Email</a>
    I hope this will help someone else too

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles