473,402 Members | 2,055 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,402 software developers and data experts.

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|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
3 1581
acoder
16,027 Expert Mod 8TB
How is the data stored in the array? Is it split before storing?
Sep 28 '08 #2
You have to mention field name as variable.
Sep 28 '08 #3
rnd me
427 Expert 256MB
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

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

Similar topics

9
by: jwedel_stolo | last post by:
Hi I'm creating a dataview "on the fly" in order to sort some data prior to writing out the information to a MS SQL table I have used two methods in order to determine the sort order of the...
12
by: pmud | last post by:
Hi, I am using teh following code for sorting the data grid but it doesnt work. I have set the auto generate columns to false. & set the sort expression for each field as the anme of that...
8
by: D. Roshani | last post by:
Hello Do you have any idea how I can create a Macro in Access which can do costume alphabetic sorting of only one column with foreign words (ISO-8859-1), I would like to define how I want...
0
by: Robert Brinson | last post by:
Hello all! I'm running .NET Framework 1.1 using VS.NET 2003. I've got a mystery with a DataGrid. Below is the definition of the DataGrid from my aspx page: </asp:datagrid><asp:datagrid...
4
by: Richard | last post by:
When i try sorting in the database, it sorts the numbers: 0 1 102 2 304 305 4 etc....
4
by: bboyle18 | last post by:
Hi, I am working with a table sorting script which can be found here http://www.workingwith.me.uk/articles/scripting/standardista_table_sorting This script works very nicely, but when there is a...
4
by: Ambica Jain | last post by:
Hi, I want custom sorting on some of the columns in the datagrid. And i am able to do the same by overriding MouseDown event. However, i need to rebind my datatable to reflect the changes in...
6
by: =?Utf-8?B?RGFu?= | last post by:
I am reposting a question from about 3 weeks ago ("sorting capability"). I have an aspx page in which I get the data from a database dynamically, through C# code, by creating a dynamic table...
1
by: sheldonlg | last post by:
I have inherited code with a TDC control. In this file, there are two javascripts of interest. One of these is a function, filter(), which is inside <script language=javascript></script>. The...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.