Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #7899 > unrolled thread

sorting columns

Started byfulio pen <fuliopen@yahoo.com>
First post2011-11-01 06:14 -0700
Last post2011-11-03 21:03 +0000
Articles 14 — 5 participants

Back to article view | Back to comp.lang.javascript


Contents

  sorting columns fulio pen <fuliopen@yahoo.com> - 2011-11-01 06:14 -0700
    Re: sorting columns Elegie <elegie@anonymous.invalid> - 2011-11-01 20:18 +0100
      Re: sorting columns fulio pen <fuliopen@yahoo.com> - 2011-11-02 05:07 -0700
        Re: sorting columns Elegie <elegie@anonymous.invalid> - 2011-11-02 13:46 +0100
          Re: sorting columns fulio pen <fuliopen@yahoo.com> - 2011-11-02 07:39 -0700
            Re: sorting columns Elegie <elegie@anonymous.invalid> - 2011-11-02 16:00 +0100
              Re: sorting columns fulio pen <fuliopen@yahoo.com> - 2011-11-02 11:06 -0700
    Re: sorting columns Dr J R Stockton <reply1144@merlyn.demon.co.uk> - 2011-11-02 19:02 +0000
      Re: sorting columns Elegie <elegie@anonymous.invalid> - 2011-11-03 02:27 +0100
      Re: sorting columns Andreas Bergmaier <andber93@web.de> - 2011-11-03 20:06 +0100
        Re: sorting columns Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2011-11-03 20:41 +0100
          Re: sorting columns Dr J R Stockton <reply1144@merlyn.demon.co.uk> - 2011-11-04 21:12 +0000
        Re: sorting columns Dr J R Stockton <reply1144@merlyn.demon.co.uk> - 2011-11-04 21:00 +0000
    Re: sorting columns Dr J R Stockton <reply1144@merlyn.demon.co.uk> - 2011-11-03 21:03 +0000

#7899 — sorting columns

Fromfulio pen <fuliopen@yahoo.com>
Date2011-11-01 06:14 -0700
Subjectsorting columns
Message-ID<f7fca7c8-769a-4339-ae49-bda395338ef3@l12g2000vby.googlegroups.com>
Dear group members:

Back in 2005, some people in this group helped me to create the
following table for sorting.

http://www.pinyinology.com/sortable/shuihu/heavenly.html

He or she did a few rows,  and I followed suit adding all other rows.
All columns in the table are for sorting.  Now I like to create
another table of three columns.  Only two columns are for sorting. The
other one is not.  Please  open the following page:

http://www.pinyinology.com/diaoHao2a/names2a.html

I have many rows for the table.  I hope some experts will do these few
rows.  And I will follow suit again adding other rows.

Thanks for expertise and help.

fulio pen

[toc] | [next] | [standalone]


#7910

FromElegie <elegie@anonymous.invalid>
Date2011-11-01 20:18 +0100
Message-ID<4eb045f2$0$24951$426a74cc@news.free.fr>
In reply to#7899
On 01/11/2011 14:14, fulio pen wrote :

Hello,

> Back in 2005, some people in this group helped me to create the
> following table for sorting.
>
> http://www.pinyinology.com/sortable/shuihu/heavenly.html
>
> He or she did a few rows,  and I followed suit adding all other rows.
> All columns in the table are for sorting.  Now I like to create
> another table of three columns.  Only two columns are for sorting. The
> other one is not.

I am not sure about what the original script would do, but isn't this 
simply a case of table sorting? I believe that there should be some good 
scripts available on the web (with strong design, fine performance, 
extended documentation...).

However, being in the mood for a bit of javascript tonight, please find 
below a quick attempt addressing your problem. There are two files used:
- the HTML file contains the table (add as many rows as you wish) and a 
script configuration (do not edit it),
- the Javascript file contains some utilities, among which the sort part 
(do not edit it as well).

Usual caveats apply. I made this relatively quickly (in about one hour), 
so this is only slightly tested, not performance-optimized, and probably 
not that flexible. Still, it's nice writing some javascript from time to 
time :)

HTH,
Elegie.

---
HTML File
---
<!doctype html>
<html>
<head>
   <title>names2a</title>
   <meta charset='utf-8' />
   <style type="text/css">
   th {background-color: #aaa;}
   tr:nth-child(odd) td {background-color: #ccc;}
   tr:nth-child(even) td {background-color: #eee;}
   .sortable {text-decoration: underline; cursor:pointer;}
   </style>
   <script type="text/javascript" src="util.js"></script>
   <script type="text/javascript">
   // Let us augment our table with a sort behavior
   window.onload = (function (evt) {
     var target = document.getElementById("tb1");
     if (target) {
       var headers = target.getElementsByTagName("th");
       var headersToSort = [headers[0], headers[2]];
       for(var ii=0; ii<headersToSort.length; ii++) {
         createSortHandler(
           headersToSort[ii],
           TableUtil.STRING_INSENSITIVE_ASC_COMPARATOR
         );
       }
     }

     function createSortHandler(target, comparator) {
       var tbody = DomUtil.findParent(target, "table").tBodies[0];
       var cellIndex = target.cellIndex;
       if (tbody) {
         target.className = "sortable";
         target.onclick = (function (evt) {
           TableUtil.sort(tbody, cellIndex, comparator);
         });
       }
     }
   });
   </script>
</head>
<body>
   <table id="tb1">
     <thead>
       <tr>
         <th>pin yin</th>
         <th>han zi</th>
         <th>English</th>
       </tr>
     </thead>
     <tbody>
       <tr>
         <td>bai<sup>2</sup> mei<sup>3</sup> jing<sup>4</sup></td>
         <td>白美静</td>
         <td>Bentley Maria</td>
       </tr>
       <tr>
         <td>bai<sup>2</sup> jun<sup>4</sup> xiong<sup>2</sup></td>
         <td>白俊雄</td>
         <td>Bentley Mike</td>
       </tr>
       <tr>
         <td>bao<sup>1</sup> cheng<sup>2</sup> yi<sup>4</sup></td>
         <td>包诚毅</td>
         <td>Boole Chris</td>
       </tr>
       <tr>
         <td>gao<sup>1</sup> an<sup>1</sup> di<sup>2</sup></td>
         <td>高安迪</td>
         <td>Grow Andy</td>
       </tr>
     </tbody>
   </table>
</body>
</html>



---
Javascript file (util.js)
---
var DomUtil = {};
var TableUtil = {};

DomUtil.findParent = (function(element, type) {
   if (!element) {
     return null;
   }
   if (element.nodeName.toLowerCase() == type.toLowerCase()) {
     return element;
   }
   return arguments.callee(element.parentNode, type);
});

DomUtil.getText = (function(node) {
   if (node.nodeType == 3) {
     return node.nodeValue;
   } else if (node.nodeType == 1) {
     var children = node.childNodes;
     var text = "";
     for (var ii=0; ii<children.length; ii++) {
       text += arguments.callee(children[ii]);
     }
     return text;
   } else {
     return "";
   }
});

TableUtil.STRING_INSENSITIVE_ASC_COMPARATOR = (function(first, second){
   var s1 = first && first.toLowerCase() || "";
   var s2 = second && second.toLowerCase() || "";
   if (s1<s2) return -1;
   if (s1>s2) return +1;
   return 0;
});

TableUtil.sort = (function (tbody, columnIndex, comparator){

   // main algorithm

   var sortableEntities = buildSortableEntityList(tbody, columnIndex);
   sortEntityList(sortableEntities, comparator);
   reflectSortOnHTML(tbody, sortableEntities);

   // helpers

   function SortableEntity(text, row) {
     this.text = text;
     this.row = row;
   }

   function buildSortableEntityList(tbody, columnIndex) {
     var entities=[];
     var rows = tbody.rows;
     var rowsCount = rows.length;
     for(var ii=0; ii<rowsCount; ii++) {
       entities.push(
         new SortableEntity(
           DomUtil.getText(rows[ii].cells[columnIndex]),
           rows[ii]
         )
       );
     }
     return entities;
   }

   function sortEntityList(entityList, comparator) {
     entityList.sort(
       function (first, second) {
         return comparator(first.text, second.text);
       }
     );
   }

   function reflectSortOnHTML(tbody, sortedEntityList) {
     for(var ii=0; ii<sortedEntityList.length; ii++) {
       tbody.appendChild(sortedEntityList[ii].row);
     }
   }

});


[toc] | [prev] | [next] | [standalone]


#7920

Fromfulio pen <fuliopen@yahoo.com>
Date2011-11-02 05:07 -0700
Message-ID<0878d6aa-6869-4b4b-a7e9-e77321b989da@h5g2000vbf.googlegroups.com>
In reply to#7910
On Nov 1, 3:18 pm, Elegie <ele...@anonymous.invalid> wrote:
> On 01/11/2011 14:14, fulio pen wrote :
>
> Hello,
>
> > Back in 2005, some people in this group helped me to create the
> > following table for sorting.
>
> >http://www.pinyinology.com/sortable/shuihu/heavenly.html
>
> > He or she did a few rows,  and I followed suit adding all other rows.
> > All columns in the table are for sorting.  Now I like to create
> > another table of three columns.  Only two columns are for sorting. The
> > other one is not.
>
> I am not sure about what the original script would do, but isn't this
> simply a case of table sorting? I believe that there should be some good
> scripts available on the web (with strong design, fine performance,
> extended documentation...).
>
> However, being in the mood for a bit of javascript tonight, please find
> below a quick attempt addressing your problem. There are two files used:
> - the HTML file contains the table (add as many rows as you wish) and a
> script configuration (do not edit it),
> - the Javascript file contains some utilities, among which the sort part
> (do not edit it as well).
>
> Usual caveats apply. I made this relatively quickly (in about one hour),
> so this is only slightly tested, not performance-optimized, and probably
> not that flexible. Still, it's nice writing some javascript from time to
> time :)
>
> HTH,
> Elegie.
>
> ---
> HTML File
> ---
> <!doctype html>
> <html>
> <head>
>    <title>names2a</title>
>    <meta charset='utf-8' />
>    <style type="text/css">
>    th {background-color: #aaa;}
>    tr:nth-child(odd) td {background-color: #ccc;}
>    tr:nth-child(even) td {background-color: #eee;}
>    .sortable {text-decoration: underline; cursor:pointer;}
>    </style>
>    <script type="text/javascript" src="util.js"></script>
>    <script type="text/javascript">
>    // Let us augment our table with a sort behavior
>    window.onload = (function (evt) {
>      var target = document.getElementById("tb1");
>      if (target) {
>        var headers = target.getElementsByTagName("th");
>        var headersToSort = [headers[0], headers[2]];
>        for(var ii=0; ii<headersToSort.length; ii++) {
>          createSortHandler(
>            headersToSort[ii],
>            TableUtil.STRING_INSENSITIVE_ASC_COMPARATOR
>          );
>        }
>      }
>
>      function createSortHandler(target, comparator) {
>        var tbody = DomUtil.findParent(target, "table").tBodies[0];
>        var cellIndex = target.cellIndex;
>        if (tbody) {
>          target.className = "sortable";
>          target.onclick = (function (evt) {
>            TableUtil.sort(tbody, cellIndex, comparator);
>          });
>        }
>      }
>    });
>    </script>
> </head>
> <body>
>    <table id="tb1">
>      <thead>
>        <tr>
>          <th>pin yin</th>
>          <th>han zi</th>
>          <th>English</th>
>        </tr>
>      </thead>
>      <tbody>
>        <tr>
>          <td>bai<sup>2</sup> mei<sup>3</sup> jing<sup>4</sup></td>
>          <td>白美静</td>
>          <td>Bentley Maria</td>
>        </tr>
>        <tr>
>          <td>bai<sup>2</sup> jun<sup>4</sup> xiong<sup>2</sup></td>
>          <td>白俊雄</td>
>          <td>Bentley Mike</td>
>        </tr>
>        <tr>
>          <td>bao<sup>1</sup> cheng<sup>2</sup> yi<sup>4</sup></td>
>          <td>包诚毅</td>
>          <td>Boole Chris</td>
>        </tr>
>        <tr>
>          <td>gao<sup>1</sup> an<sup>1</sup> di<sup>2</sup></td>
>          <td>高安迪</td>
>          <td>Grow Andy</td>
>        </tr>
>      </tbody>
>    </table>
> </body>
> </html>
>
> ---
> Javascript file (util.js)
> ---
> var DomUtil = {};
> var TableUtil = {};
>
> DomUtil.findParent = (function(element, type) {
>    if (!element) {
>      return null;
>    }
>    if (element.nodeName.toLowerCase() == type.toLowerCase()) {
>      return element;
>    }
>    return arguments.callee(element.parentNode, type);
>
> });
>
> DomUtil.getText = (function(node) {
>    if (node.nodeType == 3) {
>      return node.nodeValue;
>    } else if (node.nodeType == 1) {
>      var children = node.childNodes;
>      var text = "";
>      for (var ii=0; ii<children.length; ii++) {
>        text += arguments.callee(children[ii]);
>      }
>      return text;
>    } else {
>      return "";
>    }
>
> });
>
> TableUtil.STRING_INSENSITIVE_ASC_COMPARATOR = (function(first, second){
>    var s1 = first && first.toLowerCase() || "";
>    var s2 = second && second.toLowerCase() || "";
>    if (s1<s2) return -1;
>    if (s1>s2) return +1;
>    return 0;
>
> });
>
> TableUtil.sort = (function (tbody, columnIndex, comparator){
>
>    // main algorithm
>
>    var sortableEntities = buildSortableEntityList(tbody, columnIndex);
>    sortEntityList(sortableEntities, comparator);
>    reflectSortOnHTML(tbody, sortableEntities);
>
>    // helpers
>
>    function SortableEntity(text, row) {
>      this.text = text;
>      this.row = row;
>    }
>
>    function buildSortableEntityList(tbody, columnIndex) {
>      var entities=[];
>      var rows = tbody.rows;
>      var rowsCount = rows.length;
>      for(var ii=0; ii<rowsCount; ii++) {
>        entities.push(
>          new SortableEntity(
>            DomUtil.getText(rows[ii].cells[columnIndex]),
>            rows[ii]
>          )
>        );
>      }
>      return entities;
>    }
>
>    function sortEntityList(entityList, comparator) {
>      entityList.sort(
>        function (first, second) {
>          return comparator(first.text, second.text);
>        }
>      );
>    }
>
>    function reflectSortOnHTML(tbody, sortedEntityList) {
>      for(var ii=0; ii<sortedEntityList.length; ii++) {
>        tbody.appendChild(sortedEntityList[ii].row);
>      }
>    }
>
>
>
>
>
>
>
> });
Hello, Elegie:

Thanks a lot. Yes, this is just a case of simple table sorting. I am
deeply moved by your help. The Chinese characters and pinyin must not
be easy, if you are a non-native speaker of the Chinese language. I've
saved the code to separate files, and will study and test it
carefully.  Thanks again.

fulio pen

[toc] | [prev] | [next] | [standalone]


#7921

FromElegie <elegie@anonymous.invalid>
Date2011-11-02 13:46 +0100
Message-ID<4eb13bab$0$16579$426a74cc@news.free.fr>
In reply to#7920
On 02/11/2011 13:07, fulio pen wrote :

Hello fulio pen,

> Thanks a lot. Yes, this is just a case of simple table sorting.

Thank you for the confirmation. In that case, you would maybe be better 
off finding and using a free script on the Internet. This way, you would 
have access to a fully-tested and supported component. Of course, you 
may use the script that I have posted as well, if you like.

Unfortunately, I am not knowledgeable enough about third party 
components so as to provide you with a good suggestion; but other 
contributors could be more insightful on this matter.

> I am
> deeply moved by your help. The Chinese characters and pinyin must not
> be easy, if you are a non-native speaker of the Chinese language.

I would be glad if the script could be of some help to you. I have built 
it using the source code that you have provided, which is why it uses 
the Chinese characters (I have simply copied and pasted them into my 
editor). As a matter of fact, despite my interest for the Chinese 
culture, I cannot read nor speak Chinese, as of these days.

> I've
> saved the code to separate files, and will study and test it
> carefully.  Thanks again.

Do not hesitate if you have questions about it. As it is, the code only 
comes with a string case-insensitive ascending sort, but I believe that 
it would be easy to add a descending sort as well, and maybe some sorts 
for other data types (like numbers or dates). The configuration part 
could be improved as well (for instance supoorting a better event model, 
alternating sort algorithms on click events, and so on).

Kind regards,
Elegie.

[toc] | [prev] | [next] | [standalone]


#7925

Fromfulio pen <fuliopen@yahoo.com>
Date2011-11-02 07:39 -0700
Message-ID<135b2f01-1ca1-4941-bf0e-088bea8daebc@r2g2000vbj.googlegroups.com>
In reply to#7921
On Nov 2, 8:46 am, Elegie <ele...@anonymous.invalid> wrote:
> On 02/11/2011 13:07, fulio pen wrote :
>
> Hello fulio pen,
>
> > Thanks a lot. Yes, this is just a case of simple table sorting.
>
> Thank you for the confirmation. In that case, you would maybe be better
> off finding and using a free script on the Internet. This way, you would
> have access to a fully-tested and supported component. Of course, you
> may use the script that I have posted as well, if you like.
>
> Unfortunately, I am not knowledgeable enough about third party
> components so as to provide you with a good suggestion; but other
> contributors could be more insightful on this matter.
>
> > I am
> > deeply moved by your help. The Chinese characters and pinyin must not
> > be easy, if you are a non-native speaker of the Chinese language.
>
> I would be glad if the script could be of some help to you. I have built
> it using the source code that you have provided, which is why it uses
> the Chinese characters (I have simply copied and pasted them into my
> editor). As a matter of fact, despite my interest for the Chinese
> culture, I cannot read nor speak Chinese, as of these days.
>
> > I've
> > saved the code to separate files, and will study and test it
> > carefully.  Thanks again.
>
> Do not hesitate if you have questions about it. As it is, the code only
> comes with a string case-insensitive ascending sort, but I believe that
> it would be easy to add a descending sort as well, and maybe some sorts
> for other data types (like numbers or dates). The configuration part
> could be improved as well (for instance supoorting a better event model,
> alternating sort algorithms on click events, and so on).
>
> Kind regards,
> Elegie.

Hello Elegie:

I saved the two files as follows:

http://www.pinyinology.com/diaoHao2a/names/names3.html

http://www.pinyinology.com/diaoHao2a/names/util.js

They seem not working. When having time, could you please look at
them. I added two lines to the style section of the html file, to
define the superscript size and the cursor. They may not cause any
problem. I may have made other mistakes when saving them. Thanks again
for your help.

fulio pen

[toc] | [prev] | [next] | [standalone]


#7926

FromElegie <elegie@anonymous.invalid>
Date2011-11-02 16:00 +0100
Message-ID<4eb15afe$0$21871$426a74cc@news.free.fr>
In reply to#7925
On 02/11/2011 15:39, fulio pen wrote :

Hello,

> I saved the two files as follows:
>
> http://www.pinyinology.com/diaoHao2a/names/names3.html
>
> http://www.pinyinology.com/diaoHao2a/names/util.js
>
> They seem not working. When having time, could you please look at
> them. I added two lines to the style section of the html file, to
> define the superscript size and the cursor. They may not cause any
> problem. I may have made other mistakes when saving them. Thanks again
> for your help.

If you check the util.js file, you will notice that you miss the last 
line, which should read:

    });

This is probably just a copy-paste issue. Add it back, and it should be 
fine.

Also, note that most browsers provide a javascript console, which shows 
javascript errors. If you happen to use one of them (like Chrome or 
Firefox), then you may like and check that console, as it brings useful 
information for script authors. Such consoles are usually located under 
"Web Development" or "Tools" menus.

HTH,
Elegie.

[toc] | [prev] | [next] | [standalone]


#7935

Fromfulio pen <fuliopen@yahoo.com>
Date2011-11-02 11:06 -0700
Message-ID<ff57fcc0-3d1a-4c33-a715-68c4f0210fc8@i15g2000yqm.googlegroups.com>
In reply to#7926
On Nov 2, 11:00 am, Elegie <ele...@anonymous.invalid> wrote:
> On 02/11/2011 15:39, fulio pen wrote :
>
> Hello,
>
> > I saved the two files as follows:
>
> >http://www.pinyinology.com/diaoHao2a/names/names3.html
>
> >http://www.pinyinology.com/diaoHao2a/names/util.js
>
> > They seem not working. When having time, could you please look at
> > them. I added two lines to the style section of the html file, to
> > define the superscript size and the cursor. They may not cause any
> > problem. I may have made other mistakes when saving them. Thanks again
> > for your help.
>
> If you check the util.js file, you will notice that you miss the last
> line, which should read:
>
>     });
>
> This is probably just a copy-paste issue. Add it back, and it should be
> fine.
>
> Also, note that most browsers provide a javascript console, which shows
> javascript errors. If you happen to use one of them (like Chrome or
> Firefox), then you may like and check that console, as it brings useful
> information for script authors. Such consoles are usually located under
> "Web Development" or "Tools" menus.
>
> HTH,
> Elegie.

Hi, Elegie:

I added. And it works perfectly. Thanks a lot again. I will go the
javascript console.

fulio pen

[toc] | [prev] | [next] | [standalone]


#7941

FromDr J R Stockton <reply1144@merlyn.demon.co.uk>
Date2011-11-02 19:02 +0000
Message-ID<mqUGzLEbPZsOFwUD@invalid.uk.co.demon.merlyn.invalid>
In reply to#7899
In comp.lang.javascript message <f7fca7c8-769a-4339-ae49-bda395338ef3@l1
2g2000vby.googlegroups.com>, Tue, 1 Nov 2011 06:14:04, fulio pen
<fuliopen@yahoo.com> posted:

>
>Back in 2005, some people in this group helped me to create the
>following table for sorting.

Why sort a <table>?

Supply the data in JavaScript, as a "two-dimensional array"
  Arr[[..., ..., ...   ], [...], [...], [...], ... [...]] ;

At need, sort that.  Then remove any existing Table, build the new Table
using DOM methods, and insert the new Table.

That can give the maintainer the possible advantage that the rows of Arr
need not be supplied in any particular order.

-- 
 (c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk  Turnpike v6.05  MIME.
  Web  <http://www.merlyn.demon.co.uk/> - FAQqish topics, acronyms and links;
  Astro stuff via astron-1.htm, gravity0.htm ; quotings.htm, pascal.htm, etc.
 No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News.

[toc] | [prev] | [next] | [standalone]


#7942

FromElegie <elegie@anonymous.invalid>
Date2011-11-03 02:27 +0100
Message-ID<4eb1ee15$0$25002$426a74cc@news.free.fr>
In reply to#7941
On 02/11/2011 20:02, Dr J R Stockton wrote :

Hello John,

> Why sort a<table>?
>
> Supply the data in JavaScript, as a "two-dimensional array"
>    Arr[[..., ..., ...   ], [...], [...], [...], ... [...]] ;
>
> At need, sort that.  Then remove any existing Table, build the new Table
> using DOM methods, and insert the new Table.

This is certainly a possible approach, yet this could raise some issues 
related to browser scripting constraints. I will discuss two of them 
below (these constraints may not apply to all projects, though).


1) Javascript Accessibility

Firstly, you would have to address the constraint of javascript 
accessibility. Some target platforms may not support javascript, or may 
support it but have it disabled. In such cases, it could be reasonably 
assumed that the user would still enjoy a cleanly degraded service.

Basically, this means that, at the very least, you would want data to be 
expressed in plain HTML (so that they can still be rendered by the 
browser), and behaviors to be located on the server, and invoked through 
regular HTTP requests (i.e. clicking links). You would therefore start 
with building a basic HTML page (with the data and the links), providing 
a simple yet operable service to the javascript-deprived user.

After you have built your basic HTML page, you may consider augmenting 
it with client-side functionalities, using javascript. This is an 
important point: a client-side scripting strategy is more often a matter 
of decorating an existing view into an advanced one, rather than a 
matter of generating a fresh view from scratch.

To illustrate this strategy, let us use the table sorting example:
a) we would first build an HTML table holding all data, and would 
provide some links to have a sort executed on the server (the user would 
click a link configured with the sort options, and the page would be 
rendered back with the table being properly sorted),
b) we would then add a sorting javascript library and plug it on the 
table, so that the sort be done in the browser. We would hide the server 
links, as we would have no further use for them.

Note that you could fairly consider that table sorting is a nice-to-have 
and not a must-have functionality, and as a result only make it 
available through browser scripting (so no server-side sorting services, 
and no links to invoke them).

2) Object Identities

Replacing existing nodes in the current view, whether you use parsing 
artifacts (like innerHTML) or DOM manipulations, can be dangerous and 
should be avoided when possible.

The problem is quite simple: when you replace a node by another, you 
lose the identity of the first node. What about other scripts which 
would hold references to the old node? What about event listeners 
previously attached to the old node? By changing the underlying 
structure, you'd have them fail.

 From a theoretical point of view, this is a problem of coupling between 
a structure (the DOM tree, which represents the view) and actions 
managers (javascript algorithms). Ideally, your actions managers should 
be made as generic and decoupled as possible (like designing an API), 
and work on a structure without modifying it (otherwise you'd have some 
encapsulation breach, with a structure being managed at different places).

Sometimes though, actions managers may have to change the structure 
(like reordering nodes, or adding new nodes to the view). It is the 
responsibility of the author of the behavior to make sure that this 
alteration is properly documented, and reasonably safe (i.e. "should 
not" break any other alien script).

Kind regards,
Elegie.

[toc] | [prev] | [next] | [standalone]


#7957

FromAndreas Bergmaier <andber93@web.de>
Date2011-11-03 20:06 +0100
Message-ID<j8uonk$v6j$1@news.albasani.net>
In reply to#7941
Dr J R Stockton schrieb:
> Why sort a<table>?
Why not?
>
> Supply the data in JavaScript, as a "two-dimensional array"
>    Arr[[..., ..., ...   ], [...], [...], [...], ... [...]] ;
>
> At need, sort that.  Then remove any existing Table, build the new Table
> using DOM methods, and insert the new Table.

What do you mean with two-dimensional array? Does it represent the cell 
data, or does each second-level-array contain the relevant cell content 
(of the column you want to sort) and a reference to the row element? I 
guess it would be faster to store the dom elements, instead of 
rebuilding them.

Another, minimal approach could be:

function sort(table, column, mysortfn) {
// table a <table>-element
// column the number of the column to sort
// mysortfn a sorting function (see Array.sort documentation)
    var r = [].slice.call(table.rows, 1); // dont sort the top row
    r.sort(function(a, b) {
       return mysortfunction(
          a.cells[column].textContent,
          b.cells[column].textContent
       );
    });
    for (var i=0; i<r.length; i++)
       table.insertRow(r[i]);
}

A littlebit faster might be something like
    r = [], tr = table.rows;
    for (var i=1; i<tr.length; i++)
       r.push( [tr[i].cells[column].textContent, row] ); // slice and map
    r.sort(function(a, b) {
        return mysortfunction(a[0], b[0]);
    });
    for (var i=0; i<length; i++)
       table.insertRow(r[i][1]);

Disclaimer: I'm not sure about standard-compliancy of all browsers regarding
* <table>.rows
* <table>.insertRow(<tr>)
* <tr>.cells
* <*>.textContent
* Array.prototype.sort(fn)

  Bergi

[toc] | [prev] | [next] | [standalone]


#7960

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2011-11-03 20:41 +0100
Message-ID<8931625.SEqChMirdb@PointedEars.de>
In reply to#7957
Andreas Bergmaier wrote:

> Dr J R Stockton schrieb:
>> Why sort a<table>?
> Why not?

Because that is comparably inefficient.

>> Supply the data in JavaScript, as a "two-dimensional array"
>>    Arr[[..., ..., ...   ], [...], [...], [...], ... [...]] ;
>>
>> At need, sort that.  Then remove any existing Table, build the new Table
>> using DOM methods, and insert the new Table.
> 
> What do you mean with two-dimensional array?

There are no multi-dimensional arrays in ECMAScript implementations, only 
arrays, represented by Array instances, that can contain references to other 
Array instances as elements.

> Does it represent the cell data, or does each second-level-array contain
> the relevant cell content (of the column you want to sort) and a reference
> to the row element?

Yes.

> I guess it would be faster to store the dom elements, instead of
> rebuilding them.

If you mean references to DOM element objects, that is an interesting idea.  
The main problem with sorting the table in-situ is that this implicitly 
requires a considerable number of modifications of the node-relative 
structure.

However, you should take into account the time it takes to access a property 
of a host object, that is referred to by a property of an Array instance, 
that yields a primitive, but computed, value, compared to accessing a 
property of an Array instance that stores a primitive value (the length of 
the first part of that sentence compared to the length of the second one 
should make you think already).

> A littlebit faster might be something like
>     r = [], tr = table.rows;
>     for (var i=1; i<tr.length; i++)
>        r.push( [tr[i].cells[column].textContent, row] ); // slice and map
>     r.sort(function(a, b) {
>         return mysortfunction(a[0], b[0]);
>     });
>     for (var i=0; i<length; i++)
>        table.insertRow(r[i][1]);
> 
> Disclaimer: I'm not sure about standard-compliancy of all browsers
> regarding * <table>.rows
> * <table>.insertRow(<tr>)
> * <tr>.cells
> * <*>.textContent
> * Array.prototype.sort(fn)

Support for the `rows' and `cells' properties, and Array.prototype.sort()  
should be ubiquitous by now [1,2].  The `textContent' property, on the other 
hand, requires an implementation of the Node interface of W3C DOM Level 3 
Core, which e. g. MSHTML before version 9 does not provide [3].


PointedEars
___________
[1] <http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html>
    <http://msdn.microsoft.com/en-us/library/ms537484(VS.85).aspx>
[2] <http://pointedears.de/scripts/test/es-matrix/#a>
[3] <https://developer.mozilla.org/En/DOM/Node.textContent>
    <http://msdn.microsoft.com/en-us/library/ff974773(VS.85).aspx>
-- 
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee

[toc] | [prev] | [next] | [standalone]


#8027

FromDr J R Stockton <reply1144@merlyn.demon.co.uk>
Date2011-11-04 21:12 +0000
Message-ID<1VvyMpIxUFtOFw8r@invalid.uk.co.demon.merlyn.invalid>
In reply to#7960
In comp.lang.javascript message <8931625.SEqChMirdb@PointedEars.de>,
Thu, 3 Nov 2011 20:41:25, Thomas 'PointedEars' Lahn <PointedEars@web.de>
posted:

>Andreas Bergmaier wrote:
>
>> Dr J R Stockton schrieb:
>>> Why sort a<table>?
>> Why not?
>
>Because that is comparably inefficient.
                comparatively ?
>
>>> Supply the data in JavaScript, as a "two-dimensional array"
>>>    Arr[[..., ..., ...   ], [...], [...], [...], ... [...]] ;
>>>
>>> At need, sort that.  Then remove any existing Table, build the new Table
>>> using DOM methods, and insert the new Table.
>>
>> What do you mean with two-dimensional array?
>
>There are no multi-dimensional arrays in ECMAScript implementations, only
>arrays, represented by Array instances, that can contain references to other
>Array instances as elements.

Those adept in reading English will have considered the difference in
meaning between 'a "two-dimensional array"' and 'a two-dimensional
array'.


To address one of Elegie's points : to accommodate those without
scripting, the data can be pre-loaded into an HTML table.  Those with
script can then copy that initial data into whatever form, such as Arr
above, is thought best for sorting etc.

-- 
 (c) John Stockton, Surrey, UK.  ?@merlyn.demon.co.uk   Turnpike v6.05   MIME.
   Web  <http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.

          ECMA 5 lacks support for the speedy Quantum Bogosort.

[toc] | [prev] | [next] | [standalone]


#8026

FromDr J R Stockton <reply1144@merlyn.demon.co.uk>
Date2011-11-04 21:00 +0000
Message-ID<UW+KcZH1JFtOFwYf@invalid.uk.co.demon.merlyn.invalid>
In reply to#7957
In comp.lang.javascript message <j8uonk$v6j$1@news.albasani.net>, Thu, 3
Nov 2011 20:06:35, Andreas Bergmaier <andber93@web.de> posted:

>Dr J R Stockton schrieb:
>> Why sort a<table>?
>Why not?

Because sorting an N-element list requires something like 2 N log N
individual element reads, and maybe N log N element writes.  For those,
the sort algorithms refer to an element by its index number.  Therefore,
if the number of rows may be large, one wants to optimise the speed of
each of the N log N steps of the sort.  Using an array for the rows will
provide the simplest access to the elements being sorted.  Using arrays
for the data within the rows will provide simple access to the items to
be compared.

If the columns are numbered 1 to J, then the sort keys could be stored
in Column 0, for ready access.


>> Supply the data in JavaScript, as a "two-dimensional array"
>>    Arr[[..., ..., ...   ], [...], [...], [...], ... [...]] ;
>>
>> At need, sort that.  Then remove any existing Table, build the new Table
>> using DOM methods, and insert the new Table.
>
>What do you mean with two-dimensional array? Does it represent the cell
>data, or does each second-level-array contain the relevant cell content
>(of the column you want to sort) and a reference to the row element?

I meant that the elements of the array, if written out in the usual two-
dimensional form, would look like the actual table elements on screen.

> I guess it would be faster to store the dom elements, instead of
>rebuilding them.

That, I think, will depend strongly on the number of rows in the array;
one *must* have easy access to the values to be compared.  If it is
large, the only important thing is to optimise the actual sorting.  If
it is small, the whole thing will take very little time anyway.

-- 
 (c) John Stockton, nr London, UK.    ?@merlyn.demon.co.uk     Turnpike v6.05.
 Website  <http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
 PAS EXE etc. : <http://www.merlyn.demon.co.uk/programs/> - see in 00index.htm
 Dates - miscdate.htm estrdate.htm js-dates.htm pas-time.htm critdate.htm etc.

[toc] | [prev] | [next] | [standalone]


#7971

FromDr J R Stockton <reply1144@merlyn.demon.co.uk>
Date2011-11-03 21:03 +0000
Message-ID<LzFdlbGcGwsOFwgu@invalid.uk.co.demon.merlyn.invalid>
In reply to#7899
In comp.lang.javascript message <f7fca7c8-769a-4339-ae49-bda395338ef3@l1
2g2000vby.googlegroups.com>, Tue, 1 Nov 2011 06:14:04, fulio pen
<fuliopen@yahoo.com> posted:

>I have many rows for the table.

To add to my previous in this thread :

In that case, it should be faster if you compute for each sortable datum
of a column a sort key, attached to the datum, of such a nature that the
many comparisons used in sorting reduce to a simple comparison of
values, as a result of which the datum-key pair may be swapped as a
unit.

For example, if sorting European date strings such as 24/7/2012,
rearrange into an ISO-8601 form, 20120724 for the key.

See <http://www.merlyn.demon.co.uk/js-order.htm>.


If Elegie has a little time to spare, an E-mail to me could cure that.

-- 
 (c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk  Turnpike v6.05  MIME.
  Web  <http://www.merlyn.demon.co.uk/> - FAQqish topics, acronyms and links;
  Astro stuff via astron-1.htm, gravity0.htm ; quotings.htm, pascal.htm, etc.

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.javascript


csiph-web