Question

Sort HOF table - DanRollins

Asked by: ameba

My existing (slow) table:
http://www.geocities.com/ameba_vb/qpost/hof.html

Related questions:
http:/Web_Languages/Q_20614185.html "Client side sorting"
http:/Expert_Input/Q_20614145.html "HOF"

Dan Rollins wrote:
> Ameba, I have a new sort function for your HOF.

> It sorts in about 10 seconds (the current sort takes about 90 seconds on my computer)  It's not as' generic' as your existing sortTable.js and you will need a few minor tweaks to the first two (header) lines of the table.


Thanks!

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-06-06 at 02:00:34ID20639107
Tags

function

Topic

JavaScript

Participating Experts
2
Points
400
Comments
17

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Dan Rollins
    this is for answering http://www.experts-exchange.com/jsp/qShow.jsp?ta=mfc&qid=20131657 unfortunetly i used almost every point i had on that question so i only have 20 points left. :) emily
  2. Congrats LeeTutor (HOF)
    I see you made the HOF and wanted to say CONGRADULATIONS to a friend and EE colleague. What was the date when you made it in? Spencer The Crazy One
  3. Points for Dan Rollins
    Points relating to http://www.experts-exchange.com/Programming/Programming_Languages/Cplusplus/Q_20549425.html Thanks for your hard work, Dan.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: DanRollinsPosted on 2003-06-06 at 03:19:06ID: 8664784

//  file:  DanSortTbl.js
//
// notes to ameba:
// Put the following in the HTML page that has the table:
//
// <script src="DanSortTbl.js">
// </script>
//
// </head>
// <body bgcolor="#e8f0f8" onLoad='SetupForSortingTable("table1",2);'>
//
// This expects a 'simple' two-row header (sort key on the second row) -- RowSpan is not supported.
// so a minor tweek is needed to your header defs:
//  
//      <tr bgcolor="#cccccc" class=hdr>
//            <td &nbsp</td>
//            <td colspan=3  align="center" >Position</td>
//            <td align="center" colspan=4>Points</td>
//            <td colspan=2>Questions</td>
//            <td colspan=4>&nbsp</td>
//      </tr>
//      <tr bgcolor="#cccccc" class=hdr>
//            <td align="center"><b>Expert</b></td>
//            <td><b>05/19</b></td>
//            <td><b>06/04</b></td>
//            <td>&nbsp;</td>
//            <td align="center"><b>05/19</b></td>
//            <td align="center"><b>06/04</b></td>
//            <td align="center"><b>Change</b></td>
//            <td align="center"><b>This mth</b></td>
//            <td><b>Answ.</b></td>
//            <td><b>Asked</b></td>
//            <td><b>Comments</b></td>
//            <td><b>CPA</b></td>
//            <td><b>PPA</b></td>
//            <td><b>Reg.Date</b></td>
//      </tr>


//
// The following is not ncessary, but right-aligning most values in the table
// will look better,  In testing, I added these to your styles:
//   td {text-align:right}
//   td.lj {text-align:left}
// then modified the Expert link cells as:
//   <td class=lj><a href="http://www.exper... etc
//

//////////////////////////////////////////////////////////////////////
// start of 'snap-in' sort module
//

var clrSelected= "blue";
var clrDefault=  "black";
var sEventSetup= "onMouseOver='SetColor(this,1)' onMouseOut='SetColor(this,0)' onClick='StartSortTable({1});' ";
var ganSortOrders;
var goTheTable;
var gnKeyHdrRow= 0;
var gnFirstDataRow= 1;
var gnSortDir;  // set before sorting:  -1= desc, 1=asc
var gnSortClm;
var goLastHdrClicked;

function SetupForSortingTable( objId, nHdrRows )
{
      if ( !isNaN(nHdrRows) ) {  // optional argument
            gnKeyHdrRow= nHdrRows-1;  // save as global
      }
      var oTbl;
      if (objId.tagName == "TABLE") {
            oTbl= objId;  // passed in an object rather than an ID, OK, that's fine
      }
      else {
            oTbl= document.getElementById(objId);
      }
      gnFirstDataRow= gnKeyHdrRow+1;  

      var nClms=oTbl.rows[gnFirstDataRow].cells.length;

      for (j=0; j<nClms; j++ ) {
            var sInnerHTML=    oTbl.rows[gnKeyHdrRow].cells[j].innerHTML;
            var sNewInnerHTML= "<SPAN "+sEventSetup+ ">"+sInnerHTML+"</SPAN>";
            sNewInnerHTML= sNewInnerHTML.replace( "{1}", ""+j );

            oTbl.rows[gnKeyHdrRow].cells[j].innerHTML= sNewInnerHTML;
      }
      //------------------------------ save current sort order for each clm so can toggle on each click
      ganSortOrders= new Array();
      for (j=0; j<nClms; j++ ) {
            ganSortOrders[j]= 0; //  assume unsorted.  Will toggle to decending, then asscending
      }

      //---------------------------- grab the original unsortred data
      gaDataRows= new Array();
      var nTblRows= oTbl.rows.length;

      for (j=      gnFirstDataRow; j< nTblRows; j++ ) {
            gaDataRows[j-gnFirstDataRow]= oTbl.rows[j];
      }
      goTheTable= oTbl;
}

//-----------------------------------------------------------------------------
// handles mouseOver and mouseOut
//
function SetColor(obj, fSelected )
{
      if ( fSelected ) {
            obj.style.color= clrSelected;
            obj.style.cursor='hand';
            goLastHdrClicked= obj;
            window.status= "Click to sort by this column";
            return;
      }
      else {
            // Restoring original color
            obj.style.color= clrDefault;
            obj.style.cursor='auto';
            window.status="";
      }
}


//-----------------------------------------------------------------------------
function StartSortTable( nSortClm )
{
      window.status= "Sorting.  Please wait...";
      gnSortClm= nSortClm;
      setTimeout( "DoSortTable();", 10 );  // maybe need some events to pump...
}

//-----------------------------------------------------------------------------
function DoSortTable()
{
      if (ganSortOrders[gnSortClm]==0 ) ganSortOrders[gnSortClm]=1; // ascending
      else                              ganSortOrders[gnSortClm]=  -ganSortOrders[gnSortClm];
      gnSortDir= ganSortOrders[gnSortClm];

      //----------------------------------------------- sort -- takes about 10 secons for 10-row , 15 clm table
      gaDataRows.sort( CompareRows );

      var nClms= goTheTable.rows[gnFirstDataRow].cells.length;

      //------------------------------------------- need to create a copy of the table, and then move its data into the original table
      oTblNew= document.createElement("TABLE" );

      for (j=0; j< gaDataRows.length; j++ ) {
            var oRow= oTblNew.insertRow();
            for (k=0; k<nClms; k++ ) {
                  var oCell= oRow.insertCell();
                  oCell.innerHTML= gaDataRows[j].cells[k].innerHTML;
            }
      }
      //------------------------------------------- now store the data into the old table
      for (j=0; j< oTblNew.rows.length; j++ ) {
            for (k=0; k<nClms; k++ ) {
                  goTheTable.rows[j+gnFirstDataRow].cells[k].innerHTML= oTblNew.rows[j].cells[k].innerHTML;
            }
      }
      oTblNew= null;
      SetColor(goLastHdrClicked, 0);  // in case mouseout was ignored
      window.status= "";
}


// return -1 if r1<r2
//        +1 if r1>r2
//
function CompareRows( r1, r2 )
{
      var cellDatum1= r1.cells[gnSortClm].innerText;
      var cellDatum2= r2.cells[gnSortClm].innerText;

      if ( !isNaN(cellDatum1) && !isNaN(cellDatum1) ){
            cellDatum1 = parseFloat(cellDatum1);
            cellDatum2 = parseFloat(cellDatum2);
      }

      if (gnSortDir == 1  ) {
            if ( cellDatum1 < cellDatum2 ) return(-1);
            if ( cellDatum1 > cellDatum2 ) return(1);
      }
      else {
            if ( cellDatum1 > cellDatum2 ) return(-1);
            if ( cellDatum1 < cellDatum2 ) return(1);
      }
      return(0);
}

 

by: DanRollinsPosted on 2003-06-06 at 03:26:08ID: 8664807

As it says in the comments, the headers need to be a little simpler (this sort fn does not support rowspan) .... but it's not hard to lay them out so that they look the same as before but all the sort "buttons" on the second line.

The sorting does not provide special handling for dates.  It treats them as strings, so to get a valid sort, always show dates as YYYY-MM-DD

This does not show the hourglass cursor while sorting... did you know that just setting that up was taking several seconds?  But this does display a message in the statusbar and the cursor does stay as a hand.... indicating that something is happening.

I also forgot to put a check for IE 5+.  It needs to be at the start of the
       SetupForSortingTable
function.

-- Dan

 

by: amebaPosted on 2003-06-06 at 04:50:15ID: 8665306

Thanks, that is very fast: 105 seconds to 10-15 seconds, depending on column.
There is a problem when values are 'missing': "empty" and "-" are not sorted - what do i put in such cells?

 

by: amebaPosted on 2003-06-06 at 05:18:48ID: 8665484

Two notes:
- I don't have any js experience
- it doesn't have to be two rows header, it can be only one row:

     <tr bgcolor="#cccccc" class=hdr>
          <td align="center"><b>Expert</b></td>
          <td><b>Pos. 05/19</b></td>
          <td><b>Pos. 06/04</b></td>
          <td>&nbsp;</td>
          <td align="center"><b>Pts 05/19</b></td>
          <td align="center"><b>Pts 06/04</b></td>
          <td align="center"><b>Change</b></td>
          <td align="center"><b>This mth</b></td>
          <td><b>Answ.</b></td>
          <td><b>Asked</b></td>
          <td><b>Comments</b></td>
          <td><b>CPA</b></td>
          <td><b>PPA</b></td>
          <td><b>Reg.Date</b></td>
     </tr>

 

by: PhrogzPosted on 2003-06-06 at 06:42:51ID: 8666099

See http://phrogz.net/tmp/TableSort/ for another (my) library for a client-side sort. It will depend on the computer, but I would find it amazing if it took 10s for that table.

 

by: amebaPosted on 2003-06-06 at 07:23:17ID: 8666451

Thanks, Phrogz - it does support missing fields, but implementing it might take some time (a week) for me.
Points for your link: http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_20639429.html

 

by: DanRollinsPosted on 2003-06-06 at 09:00:29ID: 8667303

>> - it doesn't have to be two rows header, it can be only one row:

My code works if you use a one-row header, but it also works with a slightly-fancier 2-row header as in the example (it looks exactly like the original).  It's just that you need to pass in a number to let the fn know where the heading lines stop and the data begins.

-- Dan

 

by: PhrogzPosted on 2003-06-06 at 09:04:08ID: 8667332

DanRollins - if I may suggest, it's far better to use the semantic power of HTML to deliniate this information, using <thead> to specify where the header rows are, <tbody> to specify where the sortable rows are, and <tfoot> to specify any trailing rows not to sort. (This is what my library does, optionally allowing the user to specify a specific tbody--since multiple are allowed in HTML--to sort.)

 

by: DanRollinsPosted on 2003-06-06 at 15:42:16ID: 8670125

I'm sure there are a thousand ways to improve the code.  The author of the code that I'm replacing found all 1000 of them and the sort takes 90 seconds.

But The main thing is that most tables that one is likely to run across don't have a <THEAD> tag.

-- Dan

 

by: amebaPosted on 2003-06-06 at 16:32:16ID: 8670389

I'll accept Dan's code - it won't work for the HOF list, but I think I'll be able to use it in second table:
"TA (weekly) report", see http:Q_20619626.html

which doesn't have empty values - I think I understand the concept and the table structure used.

Thanks for your help and comments in code!

 

by: amebaPosted on 2003-06-06 at 16:39:32ID: 8670425

90 or 105 seconds - I was working with 10-20 rows when designing the table and I didn't notice *any* delay - it was a big surprise when I "finished" it. :-)

 

by: DanRollinsPosted on 2003-06-06 at 18:02:22ID: 8670680

Thanks for the points.
>>it won't work for the HOF list,...
ameba, it does work with the HOF list.  I used your source page for testing.  It needed only the  most minor of tweaks to the first two lines of the table (the headers) -- and I provided those in the comments.

-- Dan

 

by: amebaPosted on 2003-06-06 at 23:58:58ID: 8671851

ameba wrote:
"There is a problem when values are 'missing': "empty" and "-" are not sorted - what do i put in such cells?"

Sorry, maybe I missed something, I'll try again...

 

by: DanRollinsPosted on 2003-06-07 at 12:00:32ID: 8673485

I tried it with all three common situations in the data cells:
     <td></td>              -- totally empty
     <td>&nbsp;</td>   -- a common way to fill a cell (makes borders look correct)
     <td>-</td>             -- a dash will sort to the top (or the bottom, depending on the deisred sort order)

If you are talking about the header cells, there is a kind of problem in that there is no text to highlight.  I recommend that in the one header cell that is currently empty, you use
     <td>+/-</td>
to give the user something to click.

-- Dan

 

by: amebaPosted on 2003-06-08 at 14:10:50ID: 8677922

I tried again http://www.geocities.com/ameba_vb/qpost/hof.html and if I sort by "Position 05/19" or "Points 05/19" or "Change" it isn't working correctly:

"Position 05/19"
1
...
91
92
93
100
                           <-----
94
95
                           <-----


96
97
98
99

 

by: DanRollinsPosted on 2003-06-08 at 16:27:38ID: 8678319

Sorry.  I found the bug.  Change line #172  (in the COmpareRows function) to:

      if ( !isNaN(cellDatum1) && !isNaN(cellDatum2) ){

-- Dan

 

by: amebaPosted on 2003-06-10 at 02:15:01ID: 8689035

Thanks, Dan - that worked!  DanSortTbl.js will be in the next version of QuickPost.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...