By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,739 Members | 2,059 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,739 IT Pros & Developers. It's quick & easy.

javascript - sorting data by column according to field

P: 1
I have a a file called recs.js

It contains many records like this (each on a new line):

A("TV1219|cent53t|10 Revolutions|Time For The Revolution|incentive|5|trance|08/2003|3");
A("TV150|12txr004|2 digital|because of my dreams|triple xxx recordings|10|house|zz/1999|2");
A("TV1007|12tiv-32|2 in a room|Ahora Es (Now Is The Time)|positiva|5|house|zz/1995|5");
A("TV1271|12sbk 19|2 in a room|wiggle it|sbk records|7|oldskool|zz/1990|3");
A("TV513|nebdj059|4 strings|turn it around|nebula|5|dance|zz/2004|2");


The field data are separated by the bar character (|)

The fieldnames are: product code, catnum, artist, title, label, price, genre, release, numtrax.

(A is a function which I call which loads the data into an array)

I need a function I can call which will sort by whichever column the user chooses i.e. title or label.

Any help greatly appreciated!

Trixy
Sep 27 '08 #1
Share this Question
Share on Google+
3 Replies


acoder
Expert Mod 15k+
P: 16,027
How is the data stored in the array? Is it split before storing?
Sep 28 '08 #2

P: 3
You have to mention field name as variable.
Sep 28 '08 #3

rnd me
Expert 100+
P: 427
i went ahead and worked up an example for you.
i tried to layout what was going on with comments in each section
let me know if there's anything you need help with.


Expand|Select|Wrap|Line Numbers
  1.  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head>
  5.         <title>sorting and showing data</title>
  6. </head>
  7. <body onload="boot()">
  8.     <h1>Music Browser</h1>    
  9.     <div id='dumpData'></div>    
  10.  
  11. <script type='text/javascript'>    /* <![CDATA[ */
  12.  
  13. /*    define any/new data fields directly below. (in lut)
  14.         - list them in same order of incoming data fields
  15.         - keys missing from this list will not show, and could swap fields.
  16.         - 3 types allowed: 1=number, "str"=string, "mix"=auto number behind text*/
  17.  
  18. var lut = { 
  19.     "product code": "mix",
  20.      catnum:    "str", 
  21.     artist:    "str", 
  22.     title:        "str", 
  23.     label:    "str", 
  24.     price:    1, 
  25.     genre:    "str", 
  26.     release:    "mix", 
  27.     numtrax:    1            
  28. }  //        end type lut
  29.  
  30.  
  31. // define a global data repository :
  32.     var data = ([]);
  33.  
  34. // pre-build RegExps and cache common data globally for speed.
  35.     var fieldRX = /\s*\,\s*/g;
  36.     var packRX = /\|/g;
  37.     var mixRX = /.*\D+/g;
  38.     var fields =obKeys(lut);
  39.  
  40. function A(s){ //  data collector- outputs object of named values (in order of lut).
  41.     var ob = ({ });
  42.     var r = s.split(packRX);
  43.     for(var i=0, mx=fields.length; i<mx; i++){
  44.         var key = fields[i];
  45.         ob[  key  ] = lut[key].constructor( r[ i ] );
  46.     }
  47.     data[data.length] = ob;
  48.    return ob;
  49. }
  50.  
  51. function boot(){ // load the data and draw the table sorted by the first field
  52.     A("TV1219|cent53t|10 Revolutions|Time For The Revolution|incentive|5|trance|08/2003|3");
  53.     A("TV150|12txr004|2 digital|because of my dreams|triple xxx recordings|10|house|zz/1999|2");
  54.     A("TV1007|12tiv-32|2 in a room|Ahora Es (Now Is The Time)|positiva|5|house|zz/1995|5");
  55.     A("TV1271|12sbk 19|2 in a room|wiggle it|sbk records|7|oldskool|zz/1990|3");
  56.     A("TV513|nebdj059|4 strings|turn it around|nebula|5|dance|zz/2004|2");
  57.     draw( fields[0] );
  58. }
  59.  
  60.  
  61. //  html makers (used by Array.map) :
  62. function makeCell    (a){ return tag("td", a); }
  63. function makeButton(a){ return tag("th", "<input type='button'  onclick=' draw(this.value) ;' value='"+ a + "'  />"  ) ;  }
  64. function viewer    (a){return tag("tr", obVals(a).map(makeCell).join(""));}
  65.  
  66. // sorter functions; defines sort capabilities
  67. function sortNum(a, b) {return  a.toExponential ? a - b : parseFloat(a) - parseFloat(b);}
  68. function sortText(a, b) {return a !== b ? b.toLowerCase() < a.toLowerCase() ? 1 : -1 : 0;}
  69. function sortMixNumbers(a, b) {return  parseFloat(a.replace(mixRX,"")) -  parseFloat(b.replace(mixRX,""));  }
  70.  
  71.  
  72. function draw(sortField){  // sorts the data, and turns it into a table (render engine)
  73.     var sortFunc = lut[sortField] === 1 ? sortNum : sortText ;
  74.     if(lut[sortField]==="mix"){     sortFunc  = sortMixNumbers; }
  75.     var sorter = function (a,b){ return sortFunc( a[sortField] , b[sortField]  );}
  76.     var buff = data.sort(sorter);
  77.     if(sortField === draw.last ){ buff=buff.reverse(); draw.last = 0; } else { draw.last = sortField; }
  78.     var hd = tag("tr", fields.map(makeButton).join("\n"));
  79.     el("dumpData").innerHTML = tag( "table", hd+ buff.map(viewer).join("\n") , "cellspacing=0 cellpadding=2 border=1" );
  80. }
  81.  
  82.  
  83. //    helper and compatibility library, leave these utility functions intact!
  84. function tag(nd, tx, atts) {return ["<", nd, " ", atts, " >", tx, "</", nd, ">"].join("");}
  85. function el(tid) {if (tid.nodeName) {return tid;}  return el._ts[tid] || (el._ts[tid] = document.getElementById(tid));}; el._ts = [];
  86. function obVals(ob) {var r = [];var i = 0;for (var z in ob) {if (ob && ob.hasOwnProperty && ob.hasOwnProperty(z)) {r[i++] = ob[z];}}return r;}
  87. function obKeys(ob) {var r = [];var i = 0;for (var z in ob) {if (ob.hasOwnProperty(z)) {r[i++] = z;}}return r;}
  88. if (!Array.prototype.map) { Array.prototype.map = function (fun) {var len = this.length;if (typeof fun != "function") {throw new TypeError;}var res = new Array(len);var thisp = arguments[1];for (var i = 0; i < len; i++) {if (i in this) {res[i] = fun.call(thisp, this[i], i, this);}}return res;};}
  89.  
  90. /* ]]> */    </script></body></html>
  91.  
  92.  
Sep 29 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.