Mailing List Archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [tlug] [Javascript] Shouldn't there be a sort option on objects



On 02/06/2011 11:19 AM, Dave M G wrote:
TLUG,

Just spent the last hour or so going mental trying to apply a sort() on
an object. Turns out it only works on arrays.
Sorting an object? Would that be sorting by property name or property value?
Either way sound a bit weird to me.
Okay, fine, but then it turns out, as far as I can tell by looking
around the net, that there is no sort() on objects, which seems to me a
bit of a miss. I thought objects were supposed to be more dynamic and
flexible.

What I'm actually trying to do is sort a multidimensional object that
was created from JSON data. I found a few examples of how to do that
with an array and the sort() method. Nice, easy to implement examples.

However, sorting the data for an object seems like a nightmare. Or at
least, I haven't been able to find an example that I can parse down to
my level of understanding.

Has anyone encountered this before and found a workable solution?

For more specifics, my object looks like this

toplevel.midlevel.dataIWantToSortBy

"midlevel" is just a number that I use to order the data when I display
it. "dataIWantToSortBy" contains... uh... stuff. For now let's just say
it contains letters for alphabetical sorting.

So What I want to do is turn this:

toplevel.1.dataIWantToSortBy.value = C
toplevel.2.dataIWantToSortBy.value = A
toplevel.3.dataIWantToSortBy.value = B

Into:

toplevel.1.dataIWantToSortBy.value = A
toplevel.2.dataIWantToSortBy.value = B
toplevel.3.dataIWantToSortBy.value = C

I hope that makes sense.
Not really, I'm afraid, but maybe this will help:

If I had a set of properties/values and want to sort them by value I would probably make a set of objects, put them in an array and provide an appropriate sort function to array.sort().

something like this:

arr = [ {val: 'A', name:'XXX'}, {val:'C', name:'XXZ'},{val:'B',name:'GGG'}] ;
arr.sort(function(a,b) {
    if (a.val == b.val) return 0 ;
    if (a.val > b.val) return 1;
    return -1 ;
}) ;

/Fredric
begin:vcard
fn:Fredric Fredricson
n:Fredricson;Fredric
org:Ln4 Solutions AB
email;internet:Fredric.Fredricson@example.com
title:CTO
tel;home:+46 8 91 64 39
tel;cell:+46 70 677 58 48
version:2.1
end:vcard


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links