Second arguments for Array.prototype.sort: map function

Xavier MONTILLET xavierm02.net at gmail.com
Fri Feb 24 01:00:08 PST 2012


Yes. I don't want the transformed array sorted, I want the original array
sorted by its transofmation.

Peter got it right (except he uses > instead of a given function to compare
the two elements).

Here's and example:

var array = [ { v: 3.2 }, { v: 1.3 }, { v: 2.1 } ];
var compare = function ( a, b ) {
    return a - b;
};
var transform = function ( x ) {
    return { v: x.v - Math.floor( x.v ) };
};

var sortedArray = array.sort( compare, transform );

console.log( array.map( transform ) );// [ { v: .2 }, { v: .3 }, { v: .1 } ]
// you can see to sort it you need to take the last element and put it at
the beginning
// so you do that on array:
console.log( sortedArray );// [ {  v: 2.1 }, {v: 3.2 }, {v: 1.3 } ]

So you sort the transformed array and you apply the exact same
modifications to the original .

Is it clearer?

Sent from my smartphone.
On Feb 24, 2012 4:08 AM, "Peter Michaux" <petermichaux at gmail.com> wrote:

> I think I misunderstood your intent. Is what you want equivalent to
> the following?
>
> arr.map(function(el){return {a:el,b:f(el)};}).sort(function(x, y)
> {return x.b > y.b;}).map(function(el){return el.a;});
>
> Peter
>
> On Thu, Feb 23, 2012 at 6:12 PM, Peter Michaux <petermichaux at gmail.com>
> wrote:
> > On Mon, Feb 20, 2012 at 11:52 AM, Xavier MONTILLET
> > <xavierm02.net at gmail.com> wrote:
> >
> >> what I would like is to be able to do this:
> >>
> >> var sortedArray = array.sort( compare, f );
> >
> > I think the above is not very readable.
> >
> > The following is more readable and shows the order in which the more
> > modular parts are being applied.
> >
> > var sortedArray = array.map(f).sort(compare);
> >
> > Peter
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120224/50ad07cb/attachment-0001.html>


More information about the es-discuss mailing list