javascript - sorting data by column according to field

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • trix1210
    New Member
    • Sep 2008
    • 1

    javascript - sorting data by column according to field

    I have a a file called recs.js

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

    A("TV1219|cent5 3t|10 Revolutions|Tim e For The Revolution|ince ntive|5|trance| 08/2003|3");
    A("TV150|12txr0 04|2 digital|because of my dreams|triple xxx recordings|10|h ouse|zz/1999|2");
    A("TV1007|12t iv-32|2 in a room|Ahora Es (Now Is The Time)|positiva| 5|house|zz/1995|5");
    A("TV1271|12s bk 19|2 in a room|wiggle it|sbk records|7|oldsk ool|zz/1990|3");
    A("TV513|nebdj0 59|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
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    How is the data stored in the array? Is it split before storing?

    Comment

    • pradip030384
      New Member
      • Sep 2008
      • 3

      #3
      You have to mention field name as variable.

      Comment

      • rnd me
        Recognized Expert Contributor
        • Jun 2007
        • 427

        #4
        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.


        Code:
         
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
        		<title>sorting and showing data</title>
        </head>
        <body onload="boot()">
        	<h1>Music Browser</h1>	
        	<div id='dumpData'></div>	
        
        <script type='text/javascript'>	/* <![CDATA[ */
        
        /*	define any/new data fields directly below. (in lut)
        		- list them in same order of incoming data fields
        		- keys missing from this list will not show, and could swap fields.
        		- 3 types allowed: 1=number, "str"=string, "mix"=auto number behind text*/
        
        var lut = { 
        	"product code": "mix",
        	 catnum:	"str", 
        	artist:	"str", 
        	title:		"str", 
        	label:	"str", 
        	price:	1, 
        	genre:	"str", 
        	release:	"mix", 
        	numtrax:	1			
        }  //		end type lut
        
        
        // define a global data repository :
        	var data = ([]);
        
        // pre-build RegExps and cache common data globally for speed.
        	var fieldRX = /\s*\,\s*/g;
        	var packRX = /\|/g;
        	var mixRX = /.*\D+/g;
        	var fields =obKeys(lut);
        
        function A(s){ //  data collector- outputs object of named values (in order of lut).
        	var ob = ({ });
        	var r = s.split(packRX);
        	for(var i=0, mx=fields.length; i<mx; i++){
        		var key = fields[i];
        		ob[  key  ] = lut[key].constructor( r[ i ] );
        	}
        	data[data.length] = ob;
           return ob;
        }
        
        function boot(){ // load the data and draw the table sorted by the first field
        	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");
            draw( fields[0] );
        }
        
        
        //  html makers (used by Array.map) :
        function makeCell	(a){ return tag("td", a); }
        function makeButton(a){ return tag("th", "<input type='button'  onclick=' draw(this.value) ;' value='"+ a + "'  />"  ) ;  }
        function viewer	(a){return tag("tr", obVals(a).map(makeCell).join(""));}
        
        // sorter functions; defines sort capabilities
        function sortNum(a, b) {return  a.toExponential ? a - b : parseFloat(a) - parseFloat(b);}
        function sortText(a, b) {return a !== b ? b.toLowerCase() < a.toLowerCase() ? 1 : -1 : 0;}
        function sortMixNumbers(a, b) {return  parseFloat(a.replace(mixRX,"")) -  parseFloat(b.replace(mixRX,""));  }
        
        
        function draw(sortField){  // sorts the data, and turns it into a table (render engine)
        	var sortFunc = lut[sortField] === 1 ? sortNum : sortText ;
        	if(lut[sortField]==="mix"){	 sortFunc  = sortMixNumbers; }
        	var sorter = function (a,b){ return sortFunc( a[sortField] , b[sortField]  );}
        	var buff = data.sort(sorter);
        	if(sortField === draw.last ){ buff=buff.reverse(); draw.last = 0; } else { draw.last = sortField; }
        	var hd = tag("tr", fields.map(makeButton).join("\n"));
        	el("dumpData").innerHTML = tag( "table", hd+ buff.map(viewer).join("\n") , "cellspacing=0 cellpadding=2 border=1" );
        }
        
        
        //	helper and compatibility library, leave these utility functions intact!
        function tag(nd, tx, atts) {return ["<", nd, " ", atts, " >", tx, "</", nd, ">"].join("");}
        function el(tid) {if (tid.nodeName) {return tid;}  return el._ts[tid] || (el._ts[tid] = document.getElementById(tid));}; el._ts = [];
        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;}
        function obKeys(ob) {var r = [];var i = 0;for (var z in ob) {if (ob.hasOwnProperty(z)) {r[i++] = z;}}return r;}
        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;};}
        
        /* ]]> */    </script></body></html>

        Comment

        Working...