473,699 Members | 2,143 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sort array question

Hi, I'm using the following code to retrieve data from an xml file and
populate a javascript array. The data is then displayed in html table
form. I would like to then be able to sort by each column. Once the
array elements are split, what is the best way to sort them? Thank you.

//populate data object with data from xml file.
//Data is a comma delimited list of values
var jsData = new Array();
jsData[0] = {lib: "#field SUBLOOKUP_LIB#" ,doc: "#field SUBLOOKUP_DOC#" ,
com: "#field SUBLOOKUP_COM"} ;

//split up values for each element
var o = jsData[0];
o.lib = o.lib.split("," );
o.doc = o.doc.split("," );
o.com = o.com.split("," );

Nov 23 '05 #1
21 3206
ye*****@yahoo.c om wrote:
[...] I would like to then be able to sort by each column. Once the
array elements are split, what is the best way to sort them? [...]

//populate data object with data from xml file.
//Data is a comma delimited list of values
var jsData = new Array();
jsData[0] = {lib: "#field SUBLOOKUP_LIB#" ,doc: "#field SUBLOOKUP_DOC#" ,
com: "#field SUBLOOKUP_COM"} ;

//split up values for each element
var o = jsData[0];
o.lib = o.lib.split("," );
o.doc = o.doc.split("," );
o.com = o.com.split("," );


Since the table implies a dependency of all data in one row, it
does not make sense to sort each column array independently.

You need a different data structure, then you can apply a comparator:

// make each row an object as element of an array.
var a = [];
for (var i = 0, len = o.lib.length; i < len; i++)
{
a.push({lib: o.lib[i], doc: o.doc[i], com: o.com[i]});
}

// comparator
function sortByLibAsc(a, b)
{
if (a && b)
{
if (a.lib < b.lib)
{
return -1;
}
else if (a.lib > b.lib)
{
return 1;
}
}

return 0;
}

a.sort(sortByLi b);
PointedEars
Nov 23 '05 #2
Thomas 'PointedEars' Lahn wrote:
// comparator
function sortByLibAsc(a, b)
{
[...]
}

a.sort(sortByLi b);


a.sort(sortByLi bAsc);

of course.
PointedEars
Nov 23 '05 #3
thank you for the help Pointed, I'm getting closer.

How can I get my data to look like this...

jsData[0] = {lib:"string1", doc:"01",com:"b lah"};
jsData[1] = {lib:"string2", doc:"02",com:"b lah"};
jsData[2] = {lib:"string3", doc:"03",com:"b lah"};
jsData[3] = {lib:"string4", doc:"04",com:"b lah"};
jsData[4] = {lib:"string5", doc:"05",com:"b lah"};
jsData[5] = {lib:"string6", doc:"06",com:"b lah"};
jsData[6] = {lib:"string7", doc:"07",com:"b lah"};

....from my data object that looks like this?

//this is how I extract the data, but I need it to be in the above
format
var jsData = new Array();
jsData[0] = {lib: "#field SUBLOOKUP_LIB#" ,doc: "#field SUBLOOKUP_DOC#" ,
com: "#field SUBLOOKUP_COM"} ;

var o = jsData[0];
o.lib = o.lib.split("," );
o.doc = o.doc.split("," );
o.com = o.com.split("," );

Thanks.

Nov 23 '05 #4
ye*****@yahoo.c om wrote:
thank you for the help Pointed, I'm getting closer.
However, you should read and adhere to <http://jibbering.com/faq/#FAQ2_3>,
especially <http://www.jibbering.c om/faq/faq_notes/clj_posts.html> , if you
desire my further help.
How can I get my data to look like this...

jsData[0] = {lib:"string1", doc:"01",com:"b lah"};
jsData[1] = {lib:"string2", doc:"02",com:"b lah"};
jsData[2] = {lib:"string3", doc:"03",com:"b lah"};
jsData[3] = {lib:"string4", doc:"04",com:"b lah"};
jsData[4] = {lib:"string5", doc:"05",com:"b lah"};
jsData[5] = {lib:"string6", doc:"06",com:"b lah"};
jsData[6] = {lib:"string7", doc:"07",com:"b lah"};

...from my data object that looks like this?

//this is how I extract the data, but I need it to be in the above
format
var jsData = new Array();
jsData[0] = {lib: "#field SUBLOOKUP_LIB#" ,doc: "#field SUBLOOKUP_DOC#" ,
com: "#field SUBLOOKUP_COM"} ;

var o = jsData[0];
o.lib = o.lib.split("," );
o.doc = o.doc.split("," );
o.com = o.com.split("," );


This will do nothing (well OK, it will create array objects with one
element). There is no way the data below can be transformed into the
data above. As I wrote before, you need to post _real_ input and
output data if one is to find a viable transformation algorithm.
PointedEars
Nov 23 '05 #5
> However, you should read and adhere to <http://jibbering.com/faq/#FAQ2_3>,
especially <http://www.jibbering.c om/faq/faq_notes/clj_posts.html> , if you
desire my further help.
thanks for the hot tip!
As I wrote before, you need to post _real_ input and
output data if one is to find a viable transformation algorithm.


is this sufficient? This is as real as I can give you.

sadData[0] =
{lib:"string1,s tring2,string3, string4",doc:"0 1,02,03,04",com :"blah,blah,bla h,blah"};
and this is the format I would like to change it to:

happyData[0] = {lib:"string1", doc:"01",com:"b lah"};
happyData[1] = {lib:"string2", doc:"02",com:"b lah"};
happyData[2] = {lib:"string3", doc:"03",com:"b lah"};
happyData[3] = {lib:"string4", doc:"04",com:"b lah"};

Nov 23 '05 #6
ye*****@yahoo.c om wrote:
However, you should read and adhere to <http://jibbering.com/faq/#FAQ2_3>,
especially <http://www.jibbering.c om/faq/faq_notes/clj_posts.html> , if you
desire my further help.


thanks for the hot tip!
As I wrote before, you need to post _real_ input and
output data if one is to find a viable transformation algorithm.


is this sufficient? This is as real as I can give you.

sadData[0] =
{lib:"string1,s tring2,string3, string4",doc:"0 1,02,03,04",com :"blah,blah,bla h,blah"};
and this is the format I would like to change it to:

happyData[0] = {lib:"string1", doc:"01",com:"b lah"};
happyData[1] = {lib:"string2", doc:"02",com:"b lah"};
happyData[2] = {lib:"string3", doc:"03",com:"b lah"};
happyData[3] = {lib:"string4", doc:"04",com:"b lah"};


This will do the re-format, but not sort. I think Thomas' first post
will do that (but I haven't tried it). The original sadData array is
not modified, property names and values are stored in temporary arrays
is for convenience (shorter names, shallower access).
<script type="text/javascript">

var sadData = [
{
lib:"string1,st ring2,string3,s tring4",
doc:"01,02,03,0 4",
com:"blah,blah, blah,blah"
}
];

function processData(obj )
{
var prop; // Temp storage for property name
var oProps = []; // Store names of obj properties
var oVals = []; // Store values as arrays
var tArray = []; // Processed data

// Store property names & values converted to arrays
for ( prop in obj ){
oVals[oVals.length] = obj[prop].split(',');
oProps[oProps.length] = prop;
}

// Load property names & values into tArray
for (var i=0, m=oVals[0].length; i<m; ++i ){
tArray[i] = {};

for (var j=0, n=oProps.length ; j<n; ++j){
tArray[i][oProps[j]] = oVals[j][i];
}
}
return tArray;
}

/* What the result should look like
happyData[0] = {lib:"string1", doc:"01",com:"b lah"};
happyData[1] = {lib:"string2", doc:"02",com:"b lah"};
happyData[2] = {lib:"string3", doc:"03",com:"b lah"};
happyData[3] = {lib:"string4", doc:"04",com:"b lah"};
*/

function showObjData(obj )
{
var c, t = [];
var prop;
for (var i=0, m=obj.length; i<m; ++i){
t[i] = 'obj[' + i + '] = {';
c = 0;
for (prop in obj[i]){
if (c++ != 0) t[i] += ',';
t[i] += prop + ':"' + obj[i][prop] + '"';
}
t[i] += '}';
}
alert(t.join('\ n'));
}

var happyData = processData(sad Data[0]);
showObjData(hap pyData);

</script>

--
Rob
Nov 23 '05 #7
>This will do the re-format, but not sort. I think Thomas' first post
will do that (but I haven't tried it). The original sadData array is
not modified, property names and values are stored in temporary arrays
is for convenience (shorter names, shallower access).


Excellent. Thank you Rob. I will implement this tomorrow and see if it
solves my problem.

Nov 23 '05 #8
ye*****@yahoo.c om wrote:
^^^^^^^^^^^^^^^ ^^^^^^^^^
vvvvvvvvvvvvvvv vvvvvvvvvvvvvvv vvvvvvvvvvv
However, you should read and adhere to
<http://jibbering.com/faq/#FAQ2_3>, especially
<http://www.jibbering.c om/faq/faq_notes/clj_posts.html> , if you desire my
further help.
thanks for the hot tip!


OK, I have to be blunt: Please provide proper attribution
as you can see in postings of other people in this thread.
As I wrote before, you need to post _real_ input and
output data if one is to find a viable transformation algorithm.


is this sufficient? This is as real as I can give you.

sadData[0] =

{lib:"string1,s tring2,string3, string4",doc:"0 1,02,03,04",com :"blah,blah,bla h,blah"};

and this is the format I would like to change it to:

happyData[0] = {lib:"string1", doc:"01",com:"b lah"};
happyData[1] = {lib:"string2", doc:"02",com:"b lah"};
happyData[2] = {lib:"string3", doc:"03",com:"b lah"};
happyData[3] = {lib:"string4", doc:"04",com:"b lah"};


While Rob's approach seems viable, I find it too complicated and
inefficient. My advice for the time being is to perform both the
transformations I described in <news:25******* *********@Point edEars.de>
and <news:15******* *********@Point edEars.de> one after another.
As for the first transformation, you do not need to overwrite your
original data:

var o = sadData[0];
var mediumData = {};
mediumData.lib = o.lib.split("," );
mediumData.id = o.id.split(",") ;
mediumData.com = o.com.split("," );

Then transform `mediumData' into `happyData' as described, and
apply any comparator you would like on `happyData'.
HTH

PointedEars
Nov 23 '05 #9
RobG wrote:
This will do the re-format, but not sort. I think Thomas' first post
will do that (but I haven't tried it).
It will. Test it with `string5' instead of `string1', for example.
I re-included the comparator and its application here for convenience.
The original sadData array is not modified,
Same here.
property names and values are stored in temporary arrays is for
convenience (shorter names, shallower access).
What do you mean by "shallower access" here?
<script type="text/javascript">

var sadData = [
{
lib:"string1,st ring2,string3,s tring4",
doc:"01,02,03,0 4",
com:"blah,blah, blah,blah"
}
];

function processData(obj )
{
var prop; // Temp storage for property name
var oProps = []; // Store names of obj properties
var oVals = []; // Store values as arrays
var tArray = []; // Processed data

// Store property names & values converted to arrays
for ( prop in obj ){
oVals[oVals.length] = obj[prop].split(',');
oProps[oProps.length] = prop;
}
Iterating through the object properties more than one time is probably
faster than saving them in an array first and then iterate through that
array.
// Load property names & values into tArray
for (var i=0, m=oVals[0].length; i<m; ++i ){
tArray[i] = {};

for (var j=0, n=oProps.length ; j<n; ++j){
tArray[i][oProps[j]] = oVals[j][i];
}
}
return tArray;
}

[...]
function showObjData(obj )
{
var c, t = [];
var prop;
for (var i=0, m=obj.length; i<m; ++i){
t[i] = 'obj[' + i + '] = {';
c = 0;
for (prop in obj[i]){
if (c++ != 0) t[i] += ',';
t[i] += prop + ':"' + obj[i][prop] + '"';
}
t[i] += '}';
}
alert(t.join('\ n'));
}

var happyData = processData(sad Data[0]);
showObjData(hap pyData);

</script>


As I said in <news:17******* *********@Point edEars.de> and as you
recognized, two transformations are necessary here. However, it
is still possible to increase efficiency and universality.

Compare:

var
sadData = [
{lib: "string1,string 2,string3,strin g4",
doc: "01,02,03,0 4",
com: "blah,blah,blah ,blah"}
],
o = sadData[0],
p,
mediumData = {},
maxLen = 0,
len;

for (p in o)
// this implies no order of properties; if order is important,
// one has to set up an appropriate algorithm, perhaps one using
// ["property1" , "property2" , "property3"]
{
mediumData[p] = o[p].split(",");

if (maxLen < (len = mediumData[p].length))
{
maxLen = len;
}
}

// formatted output
Object.prototyp e.toString = function()
{
var a = [];
a.push("\n{");
for (var p in this)
{
a.push(p, " = ", this[p], "\n");
}
a.push("}\n");
return a.join("");
}

// debugging
alert(mediumDat a);

var happyData = [];
for (var i = 0; i < maxLen; i++)
// or (var i = maxLen; i--;) since it's sorted later anyway.
{
happyData[i] = {};

for (p in o)
{
happyData[i][p] = mediumData[p][i];
}
}

// debugging
alert(happyData );

// comparator
function sortByLibAsc(a, b)
{
if (a && b)
{
if (a.lib < b.lib)
{
return -1;
}
else if (a.lib > b.lib)
{
return 1;
}
}

return 0;
}

// apply the comparator
happyData.sort( sortByLibAsc);

// debugging
alert(happyData );
Regards,
PointedEars
Nov 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3753
by: its me | last post by:
Let's say I have a class of people... Public Class People Public Sex as String Public Age as int Public Name as string end class And I declare an array of this class...
40
4286
by: Elijah Bailey | last post by:
I want to sort a set of records using STL's sort() function, but dont see an easy way to do it. I have a char *data; which has size mn bytes where m is size of the record and n is the number of records. Both these numbers are known
7
25169
by: ritchie | last post by:
Hi all, I am new to this group and I have question that you may be able to help me with. I am trying to learn C but am currently stuck on this. First of all, I have a function for each sort (Bubble, insertion, selection..). I have an array of int's and am passing them to each sort function.
9
22057
by: Steve Wasser | last post by:
I need to sort a two-dimensional array. Each day I process a file with 9 comma-delimited fields, and varying amount of records (lines). I want to pull in each line, split it according to the comma into a two dimensional array (Perl has it f'r crissake), and sort by one of the fields (Purchase Order #). Trouble is, Array.Sort only supports single dimension arrays. Originally I was thinking of making a jagged array, pulling out the Purchase...
5
2838
by: Jan Smith | last post by:
I've searched the overloads for the Array.Sort method, and I haven't found a clear answer to my question. Maybe it's not in Array.Sort. Here's the question: I initialize an array X with the values 28 142 3 17 225. I can sort this array in ascending order and it will return 3 17 28 142 225. But I want a method that will return the sort order, not the array in sorted
48
4469
by: Alex Chudnovsky | last post by:
I have come across with what appears to be a significant performance bug in ..NET 2.0 ArrayList.Sort method when compared with Array.Sort on the same data. Same data on the same CPU gets sorted a lot faster with both methods using .NET 1.1, that's why I am pretty sure its a (rather serious) bug. Below you can find C# test case that should allow you to reproduce this error, to run it you will need to put 2 data files into current directory...
4
3034
by: Balaskas Evaggelos | last post by:
Hi, does anyone know how i can sort a multi-dimensional array by a specific field ? for example i want to sort arr where n=2, but i need the data of every array to follow that order. example array: arr
7
5063
by: ^cypis^ vel. SQ9JTI | last post by:
Hi, i need your help. I have to prepare a homework, easy program, which will be sorting the values from txt file and writing the solution to another txt file. It has to be a bucket sort. Have anyone a source code for this sample? Many thanks in advance! Regards, Luke
3
10553
by: raylopez99 | last post by:
This is an example of using multiple comparison criteria for IComparer/ Compare/CompareTo for List<and Array. Adapted from David Hayden's tutorial found on the net, but he used ArrayList so the format was different. Basically you can sort a class having members LastName (string), FirstName (string) and Age (int) according to whether you want to sort by Last Name, First Name or Age, using the .Sort function
0
8694
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
8621
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9182
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9041
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8928
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8890
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5877
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3060
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2355
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.