473,883 Members | 2,268 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
21 3237
Thomas 'PointedEars' Lahn wrote:
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?


I meant using references lower down the the scope chain to reduce the
length of lookups (I think I only cut down one level anyway). Compare
with your:

o = sadData[0],
[...]
// 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.


I think the two approaches are very similar - you store the values in a
single object that is a modified copy of the original (mediumData with
the values changed to arrays), I've used an intermediate step of
separate arrays for property names and values that are then used to
build the new object.

I like the elegance of your approach, I originally did it the same way
but was modifying the original object - I wanted to change that and used
arrays out of habit I suppose.
[...]
As I said in <news:17******* *********@Point edEars.de> and as you
For some reason I can't locate messages in Thunderbird using the message
ID. I'm sure it used to do it... there's a 'find message by id'
extension for the Mozilla news reader, maybe I'll change to that.
[...] 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;
}
}


An issue for the OP to address is what to do if there are a different
number of values in each comma-separated 'record' - should empty
elements be inserted? Is that allowed to occur? It seems to me the
original data structure is deficient, the relationship between items is
their position in the array rather than some explicit link (though that
would mean a bigger data structure).

[...]

You solution is great, I've yet to fully understand the pros/cons of
adding functions to prototypes, building objects or keeping them as
plain functions so tend to stick to the latter.

--
Rob
Nov 23 '05 #11
VK

ye*****@yahoo.c om wrote:
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("," );


As you may notice your data table stays under 90 degrees angle against
the needed position (thus records are going vertically).

So the first thing you need to pivot your table

[0]
// retrieve data - your orginal code:
sadData =
{lib:"string1,s tring2,string3, string4",
doc:"01,02,03,0 4",
com:"blah1,blah 2,blah3,blah4"} ;

var tmp = [];
tmp[0] = sadData.lib.spl it(',');
tmp[1] = sadData.doc.spl it(',');
tmp[2] = sadData.com.spl it(',');

[1]
// pivot table:
var arr = [];
for (i=0; i<tmp[0].length; i++) {
arr[i] = [tmp[0][i],tmp[1][i],tmp[2][i]];
}

[2]
// JavaScript array is not really multidimensiona l -
// it's so called "jagged array" - a single dimension array
// having other arrays as its elements. Besides other
// interesting things it also means that you can apply
// sort() method right on the top dimension w/o
// ant additional transformations :

function sortByStringDow n(a,b) {
var i = sortByStringDow n.args;
if (b[i] < a[i]) {return -1;}
else if (b[i] > a[i]) {return 1;}
else {return 0;}
}

sortByStringDow n.args = 0;
// This will sort recods by the first field in descending order:
arr.sort(sortBy StringDown);

Nov 23 '05 #12
RobG wrote:
Thomas 'PointedEars' Lahn wrote:
RobG wrote:
[snipped because of "ACK :)"]
As I said in <news:17******* *********@Point edEars.de> and as you
For some reason I can't locate messages in Thunderbird using the message
ID. I'm sure it used to do it... there's a 'find message by id'
extension for the Mozilla news reader, maybe I'll change to that.


The Message-ID Finder extension is probably provided along with your
installer version of SeaMonkey. It is also available for Thunderbird
and works fine in my v1.0.7/Linux (although I seldom need it) :)

<http://messageidfinder .mozdev.org/>
[...]
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;
}
}
An issue for the OP to address is what to do if there are a different
number of values in each comma-separated 'record' - should empty
elements be inserted? Is that allowed to occur?


`empty' is not precise. It turns out that if a value is omitted, how
it ends up in the transformed data depends on how it was omitted:

a) ",foo,bar" => ""; "foo"; "bar"
"foo,,bar" => "foo"; ""; "bar"
"foo,bar," => "foo"; "bar"; ""

b) "foo,bar" if other property strings have more than two values
=> "foo"; "bar"; undefined

"foo,bar" if other property strings have no more than two values
=> "foo"; "bar"

(read `"foo,bar"' as

[{property1: "foo,bar", property2: ..., ...}]

and `"foo"; "bar"' as

[{property1: "foo", property2: ..., ...},
{property1: "bar", property2: ..., ...},
...] )

That is why I introduced the `maxLen' variable. The maximum number of
comma-separated elements per property determines the number of "rows"
(i.e. the array length) in the transformed data.
It seems to me the original data structure is deficient, the relationship
between items is their position in the array rather than some explicit
link (though that would mean a bigger data structure).
ACK
[...]
You solution is great, I've yet to fully understand the pros/cons of
adding functions to prototypes, building objects or keeping them as
plain functions so tend to stick to the latter.


Thank you :) In case of any questions, do not hesitate to ask.
\V/ PointedEars
Nov 23 '05 #13
VK wrote:
So the first thing you need to pivot your table
[...]


Nice solution (a little bit inefficient, though).
However, the OP needed an Object object, not an array.
PointedEars
Nov 23 '05 #14
VK

Thomas 'PointedEars' Lahn wrote:
VK wrote:
So the first thing you need to pivot your table
[...]


Nice solution (a little bit inefficient, though).
However, the OP needed an Object object, not an array.


As I'm reading the OP he needed to sort *array* of records. As I stated
before by staying withing the array only (w/o array<>hashtabl e
transformations ) we are saving precious millis for the whole process.
I know that it is only bacause of the broken implementation on every
each JavaScript enabled computer (because Object and Array are really
the same). But if the implentation is guaranteed to be broken of every
single platform - why do not exploit it?

;-))

Nov 23 '05 #15
VK said the following on 11/18/2005 5:35 AM:
Thomas 'PointedEars' Lahn wrote:
VK wrote:

So the first thing you need to pivot your table
[...]
Nice solution (a little bit inefficient, though).
However, the OP needed an Object object, not an array.

As I'm reading the OP he needed to sort *array* of records.


He may have thought he needed to sort arrays but sometimes a better
solution involves using some other mechanism than what is originally though.

As I stated before by staying withing the array only (w/o array<>hashtabl e
transformations ) we are saving precious millis for the whole process.
What does this have to do with array<>hashtabl es?
I know that it is only bacause of the broken implementation on every
each JavaScript enabled computer (because Object and Array are really
the same).
Huh? Arrays and Objects are *not* the same thing. We keep telling you
that and you keep ignoring it.
But if the implentation is guaranteed to be broken of every
single platform - why do not exploit it?


Nothing is guaranteed on the Web. Especially not Browser Behavior.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 23 '05 #16
VK wrote:
Thomas 'PointedEars' Lahn wrote:
VK wrote:
> So the first thing you need to pivot your table
> [...]
Nice solution (a little bit inefficient, though).
However, the OP needed an Object object, not an array.


As I'm reading the OP he needed to sort *array* of records. [...]


No, his array `jsData' has (perhaps misguidedly) only one element,
`jsData[0]'. The basic original data is that element, an (extended)
Object object where he first wanted to split each property's string
value into an array (I helped him with that in another thread, see
<URL:news:25*** *************@P ointedEars.de>) ,
but in fact he wanted them to be arranged so that they can be sorted
easily by a named criterion.

He has clarified input and expected output format for the transformation
in <URL:news:11*** *************** ****@g14g2000cw a.googlegroups. com>,
long enough (ca. 31 standard hours) before your followup.

And finally, both RobG and me already found an appropriate solution
in <URL:news:MB*** **********@news .optus.net.au> et seqq. and
<URL:news:17*** *************@P ointedEars.de>, ca. 30 standard hours
and ca. 23 standard hours before your followup.

That is not at all to say your posting was irrelevant or in some other
way a Bad Thing, however it did not address the OPs expectations. Since
this is a newsgroup and not a support forum, that is fine with me. But
you should at least acknowledge it.
[misconceptions]


As always recommended, you should get informed _before_ you post.
HTH & HAND

PointedEars
Nov 23 '05 #17
VK

Randy Webb wrote:
He may have thought he needed to sort arrays but sometimes a better
solution involves using some other mechanism than what is originally though.
Mmm... Sorting is possible only on objects supporting IComparable
interface. Such are *for example* Array or String.
Object object doesn't have IComparable interface so a sentence like
"you need objects to sort" is meaningless to my *humble* mind.
Huh? Arrays and Objects are *not* the same thing. We keep telling you
that and you keep ignoring it.


Do you care for one more attempt? Because this topic was discussed
here:
<http://groups.google.c om/group/comp.lang.javas cript/browse_frm/thread/039e84717c0978d 9/188f8dd6f2af8fe 7?hl=en#188f8dd 6f2af8fe7>

and I got nothing but explanations how stupid am I and that the Object
or Array performance are the same. After that actually I had to conduct
my own research for the best performance. Results are posted here.

Actually skip on explanations - I'm too tired of this crap. Other code
is based on the proper understanding of Object and Array nature, my
code is based on a broken implementation exploit which is not
guaranteed to be presented everywhere.
OP is free to choose whatever he wants.
But if the implentation is guaranteed to be broken of every
single platform - why do not exploit it?


Nothing is guaranteed on the Web. Especially not Browser Behavior.


True. Let me re-phrase it: it is guaranteed on those 5 browsers I do
anyhow care of.

Nov 23 '05 #18
VK wrote:
Randy Webb wrote:
He may have thought he needed to sort arrays but sometimes a better
solution involves using some other mechanism than what is originally
though.
Mmm... Sorting is possible only on objects supporting IComparable
interface. Such are *for example* Array or String. Object object
doesn't have IComparable interface


I beg your pardon? This is J(ava)Script/ECMAScript, _not_ Java. There
is no IComparable interface, apart from the W3C DOM interfaces (which
are not part of the language) there are _no_ interfaces at all. The
relevant Object and Array specifications can be found in ECMAScript
Edition 3 Final, not in the Sun Java (2) Platform API Specification.
so a sentence like "you need objects to sort" is meaningless to my
*humble* mind.
Where is that sentence? Right, it is nowhere, you invented it from
what you understood was meant. Again.
Huh? Arrays and Objects are *not* the same thing. We keep telling you
that and you keep ignoring it.


Do you care for one more attempt? Because this topic was discussed
here:

<http://groups.google.c om/group/comp.lang.javas cript/browse_frm/thread/039e84717c0978d 9/188f8dd6f2af8fe 7?hl=en#188f8dd 6f2af8fe7>
and I got nothing but explanations how stupid am I
To include one of my favorite quotes: "Stupid is as stupid does."

You stated boldly several times in this thread something that could
be easily dismissed as nonsense due to hard fact, without being able
to provide any hard evidence that backed up your statement or your
argument. Again.

However, as I recall, nobody called you stupid or implied that you are.
I, for one, called your _argument_ nonsense because it was, from a very
objective point of view (for example you referred to CDATA in terms of
JS core string values). Lasse, Richard and I tried (and obviously
failed) to explain to you that your whole argument is based on several
basic misconceptions, such as that the ECMAScript specification did not
matter. As you insisted you be right anyway and dismissed all provided
evidence out of hand, the tone got a little bit darker.
and that the Object or Array performance are the same.


They probably are. This has nothing to do with performance, it has to do
with data structure.

Object objects are objects. Array objects are objects. However, Array
objects (i.e. objects derived from the built-in Array object) provide more
features than Object objects (i.e. objects derived from the built-in Object
object) and handle the creation of properties in a slightly different way
(so that certain numbered properties become array elements, as Lasse
explained). That is why you will have a hard time sorting object
properties of a single Object object and will have not sorting array
elements of a single Array object.

However, this thread was about how to sort Object objects that are elements
of an array _within that array_ regarding a criterion which happened to be
the value of a common property of those Object objects.
> But if the implentation is guaranteed to be broken of every
> single platform - why do not exploit it?

Nothing is guaranteed on the Web. Especially not Browser Behavior.


True. Let me re-phrase it: it is guaranteed on those 5 browsers I do
anyhow care of.


Name the browsers you are talking of (with unforged User-Agent header
value) and the behavior you consider broken regarding what you think
is relevant to this thread.
PointedEars
Nov 23 '05 #19
Thomas 'PointedEars' Lahn wrote:
RobG wrote:

Thomas 'PointedEars' Lahn wrote:
RobG wrote:
[snipped because of "ACK :)"]
As I said in <news:17******* *********@Point edEars.de> and as you


For some reason I can't locate messages in Thunderbird using the message
ID. I'm sure it used to do it... there's a 'find message by id'
extension for the Mozilla news reader, maybe I'll change to that.

The Message-ID Finder extension is probably provided along with your
installer version of SeaMonkey. It is also available for Thunderbird
and works fine in my v1.0.7/Linux (although I seldom need it) :)

<http://messageidfinder .mozdev.org/>

[...]

Installed the Thunderbird extension - works like a charm. Thanks!
--
Rob
Nov 23 '05 #20

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

Similar topics

4
3775
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
4371
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
25177
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
22088
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
2846
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
4504
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
3042
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
5069
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
10565
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
9953
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
9799
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
11166
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...
1
10868
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,...
1
7980
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5808
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6009
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4623
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
3
3242
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.