
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
- Date: Mon, 07 Feb 2011 00:00:27 +0100
- From: Fredric Fredricson <Fredric.Fredricson@example.com>
- Subject: Re: [tlug] [Javascript] Shouldn't there be a sort option on objects
- References: <4D4E75AB.5060703@example.com>
- User-agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US;	rv:1.9.2.13) Gecko/20101209 Fedora/3.1.7-0.35.b3pre.fc13	Thunderbird/3.1.7
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