Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #19635

Sorting arrays of objects (was: About keeping my array 1 based after having sorted it)

Path csiph.com!usenet.pasdenom.info!gegeweb.org!usenet-fr.net!feeder1-2.proxad.net!proxad.net!feeder2-2.proxad.net!newsfeed.arcor.de!newsspool2.arcor-online.net!news.arcor.de.POSTED!not-for-mail
Content-Type text/plain; charset="UTF-8"
Message-ID <9570287.vLAVuxmI2c@PointedEars.de> (permalink)
From Thomas 'PointedEars' Lahn <PointedEars@web.de>
Reply-To Thomas 'PointedEars' Lahn <usenet@PointedEars.de>
Organization PointedEars Software (PES)
Date Sun, 05 May 2013 01:00:16 +0200
User-Agent KNode/4.8.5
Content-Transfer-Encoding 8Bit
X-Face %i>XG-yXR'\"2P/C_aO%~;2o~?g0pPKmbOw^=NT`tprDEf++D.m7"}HW6.#=U:?2GGctkL,f89@H46O$ASoW&?s}.k+&.<b';Md8`dH6iqhT)6C^.Px|[=M@7=Ik[_w<%n1Up"LPQNu2m8|L!/3iby{-]A+#YE}Kl{Cw$\U!kD%K}\2jz"QQP6Uqr],./"?;=4v
Face iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEXTxa4RFk5dUWANED8PFEfy7+MGBiW+n3ZNF/QuAAACaElEQVQ4jVXUwVOcMBQG8Dc7Rc4PUntdWV2uxjDpGaGeozOp1woar4jd5t/v9wLstMwsA/ntlxdCAgUc1hjTc9/JCZfGoo3wG3HdmdAWrIJRHe7GM/TmpY5VFefuVcAkkPbLIaN8rmPmjloyZxgyR3GuJ4K0AGtJ2htz8o7yqikm759fldQXaMpbDzjKAG+8v+AugVTOPO5DOjLvGtUYQwh0CPjnVMyGd+8/GfUB5nLKJDD2aLDh5HYyMDJGDwQIo2ZmZcKbowNmAdB/AzyFhrmF2MHRb0QJJfaAnwGB6orZhoykLzJtGwF/xpYxI1dswomiUj3gTuAIqCn/4C7cULwGNBtwMTk3Y4LfKB5YUaOKBKYtpplm7u0vip8tU1NWWyI/7XdcSuIDoMt6rVHMWT0DbjHPGqDqZVSa6zleLcUTcIKLoMv3ueJluALtAo9B302zPPlrtiVScRdCjXvVh3e3JpYa/jjkuC9N+LrBMlz/eAN4eQijX2EdLo6c5tGGHwLyHFtXk89dDGHwCVhG9T0S/j55AhRZgkMCmUQXJ49TnS1wnQDvw0eAh9ICeMmEFbCnPMFzjAvsWoEWEFdYEx+S0MoUZ1gT1wId8+AF3Bl2OoEu906AUHx5VLw/gXYg/x84loOah/2UYNrgiwSwGO7RfUzVBbx/kgpckumGOi6QirtD6gkLTitbnxNol47S2jVc2vsN5kPqaAHT8uUdAJM4v/DanjYOwmUjWznGfwB7sGtAtor5BgofDuzaRj4kSQAqDakTsKORa3Q3xKi3gE1fhl71KRMqrdZ2AWNNg/YOhQyrVBnb+i+nEg4bsDA+egAAAABJRU5ErkJggg==
Subject Sorting arrays of objects (was: About keeping my array 1 based after having sorted it)
Newsgroups comp.lang.javascript
References <klrbhd$duk$1@dont-email.me> <c0affca3-9adb-40c0-bcdd-3222defbd338@a8g2000yqp.googlegroups.com> <12786665.ZbpLptdNGN@PointedEars.de> <bd93fc08-185a-4614-91c2-a78ea5b6beaa@n11g2000yqe.googlegroups.com> <4320221.o7mTL0IePv@PointedEars.de> <42a7e3a8-0fc0-4a5d-8809-312503f14f28@z10g2000yqd.googlegroups.com>
MIME-Version 1.0
Lines 175
NNTP-Posting-Date 05 May 2013 01:00:17 CEST
NNTP-Posting-Host da785330.newsspool3.arcor-online.net
X-Trace DXC=m[n\eQdG[gLI7\_^6>c20JMcF=Q^Z^V3H4Fo<]lROoRA8kF<OcfhCOK?F<P;FJ26_BDZm8W4\YJNLb@mF9jNikdEBoKGPB=12AGZ0YRL7in64L
X-Complaints-To usenet-abuse@arcor.de
Xref csiph.com comp.lang.javascript:19635

Show key headers only | View raw


Scott Sauyet wrote:

> Thomas 'PointedEars' Lahn wrote:
>> Scott Sauyet wrote:
>>> Thomas 'PointedEars' Lahn wrote:
>>>> ______
>>>> ¹  However, this gives me the idea that it could be useful that
>>>> jsx.array.getComparator() could also be passed a callback or
>>>> constructor for each key, or all keys, whose return value would be used
>>>> as operand in the comparison.  What do you think?
>>>
>>> I'm not sure what you would mean by "or all keys" unless you mean for
>>> each independently,
>>
>> Currently you can configure the sort method (numeric or generic), sort
>> order (ascending or descending), and strictness (strict or loose
>> equality) of the sorting both for each key separately and for all keys
>> specified in the factory call.  The same approach would be applied to the
>> callback/constructor options.
> 
> Yes, I did understand the code.  I just didn't see how supplying the
> same constructor or callback for all properties would be useful.
> Which means, I think, that I'm probably misunderstanding in general.

[This method, which is a (Function) factory, is now 
jsx.array.createComparator() to avoid confusion with getters.]

If the values of all (sort) keys are of the same type, and they are to be 
compared as if they were of another type, it should not be necessary to 
write

  var comparator = jsx.array.createComparator([
    {key: "x", callback: myConverter},
    {key: "y", callback: myConverter}
    {key: "z", callback: myConverter}
  ]);

instead of

  var comparator = jsx.array.createComparator(["x", "y", "z"], {
    callback: myConverter
  });

Same for “constructor” and “comparator”.  DRY.
 
>>> If the objects you want to sort have a property more complex than a
>>> String or Number but that still has an intrinsic order, it would be nice
>>> to be able to include that in your comparator.  But rather than a
>>> callback/constructor, how about recursively applying another comparator
>>> for that key?
>>
>> I do not see how this could work.  The elements of the Array are to be
>> sorted by a property of the objects referred by the Array elements; the
>> properties of the object's that are referred by the Array's elements are
>> not to be modified.
> 
> Perhaps I'm misunderstanding your suggestion.

ISTM you understand correctly.

> My idea is probably best given with an example.  If you had an array of
> objects structured something like this:
> 
>     myCar {
>       year: 2003,
>       manufacturer: "Dodge",
>       make: "Neon",
>       color: "red",
>       engine: {
>         liters: 2.0,
>         cylinders: 4
>       },
>       doors: 4
>       // ...
>     }
> 
> Then I might want to make a comparator with code something like this
> (please forgive me if I misuse your API; I haven't actually tried it):
> 
>     var myComparator = jsx.array.getComparator([
>       "year",
>       "manufacturer",
>       "model",
>       {
>         key: "engine",
>         comparator: jsx.array.getComparator([
>           "cylinders",
>           "liters"
>         ])
>       }
>     ]);
> 
> That internal `getComparator` call was what I was suggesting.  It
> seems to me to be a great way of offereing additional flexibility.

Yes, that is a Good Idea.  It is easier to implement and use, and more 
efficient than having the outer comparator iterate over subkeys.  
Implemented.

> Is this similar to what you wanted to do?  Would it cover the same
> ground?  It's clearly not as powerful as offering an arbitrary
> function, but it might do much of what one would want to with such a
> function, no?

[It turns out that one can eat this cake *and* have it.]

If the “callback” property is specified, the original sort value is 
converted by passing the value to it, and using its return value as the new 
sort value.

If the “constructor” (own) property is specified, the original or previous 
sort value is converted by passing it to the constructor, and using the 
returned object value as the new sort value.

If the “comparator” property is specified, it takes precedence over the 
default comparison, using the original sort value or one of the previous 
sort values.  If either the outer key is the last key, or if the inner 
comparator returns a value not equal to 0, the return value of the specified 
comparator is returned; otherwise the values of the next keys are 
considered.

That is,

  function Bar (baz)
  {
    this.baz = String(baz);
  }

  Bar.prototype.toString = function () {
    return this.baz;
  };

  function Baz (bla)
  {
    this.length = bla.length;
  }

  var foo = [
   {"bar": new Bar("burpbarbazbla")},
   {"bar": new Bar("foo")}
  ];

  var _createComparator = jsx.array.createComparator;

  foo.sort(_createComparator(["bar"], {
    callback: String,
    constructor: Baz,
    comparator: _createComparator(["length"], {numeric: true})
  }));

results in “foo” holding a reference to the equivalent of

  [
    {"bar": new Bar("foo")},
    {"bar": new Bar("burpbarbazbla")}
  ]

because:

  1a. String(new Bar("burpbarbazbla")) === "burpbarbazbla"
  1b. String(new Bar("foo"))           === "foo"
  2a. new Baz("burpbarbazbla") returns {length: 13} : Baz
  2b. new Baz("foo")           returns {length:  3} : Baz
  3a. new Baz("burpbarbazbla").length === 13
  3b. new Baz("foo").length           ===  3
  4.  3 < 13

The unit test is now available at 
<http://PointedEars.de/scripts/test/array>.

-- 
PointedEars

Twitter: @PointedEars2
Please do not Cc: me. / Bitte keine Kopien per E-Mail.

Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

About keeping my array 1 based after having sorted it "Tony" <tony.johansson@inport.com> - 2013-05-01 17:18 +0200
  Re: About keeping my array 1 based after having sorted it Daniel Pitts <newsgroup.nospam@virtualinfinity.net> - 2013-05-01 08:26 -0700
    Re: About keeping my array 1 based after having sorted it "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2013-05-01 19:43 +0200
      Re: About keeping my array 1 based after having sorted it Daniel Pitts <newsgroup.nospam@virtualinfinity.net> - 2013-05-01 15:15 -0700
        Re: About keeping my array 1 based after having sorted it "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2013-05-02 09:35 +0200
          Re: About keeping my array 1 based after having sorted it Denis McMahon <denismfmcmahon@gmail.com> - 2013-05-02 14:31 +0000
      Re: About keeping my array 1 based after having sorted it Denis McMahon <denismfmcmahon@gmail.com> - 2013-05-01 22:12 +0000
        Re: About keeping my array 1 based after having sorted it "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2013-05-02 09:36 +0200
  Re: About keeping my array 1 based after having sorted it Scott Sauyet <scott.sauyet@gmail.com> - 2013-05-02 08:52 -0700
    Re: About keeping my array 1 based after having sorted it Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2013-05-03 01:26 +0200
      Re: About keeping my array 1 based after having sorted it Scott Sauyet <scott.sauyet@gmail.com> - 2013-05-03 08:53 -0700
        Re: About keeping my array 1 based after having sorted it Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2013-05-03 18:39 +0200
          Re: About keeping my array 1 based after having sorted it Scott Sauyet <scott.sauyet@gmail.com> - 2013-05-03 11:00 -0700
            Sorting arrays of objects (was: About keeping my array 1 based after having sorted it) Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2013-05-05 01:00 +0200
              Re: Sorting arrays of objects (was: About keeping my array 1 based after having sorted it) Scott Sauyet <scott.sauyet@gmail.com> - 2013-05-05 08:53 -0700
        Re: About keeping my array 1 based after having sorted it Dr J R Stockton <reply1300@merlyn.demon.co.uk.invalid> - 2013-05-04 16:14 +0100

csiph-web