Second arguments for Array.prototype.sort: map function

Xavier MONTILLET xavierm02.net at gmail.com
Mon Feb 20 11:52:12 PST 2012


Hi,

I think it'd be nice to have a second argument for
Array.prototype.sort. It'd be a function used to map the values before
the comparison.

var array = [ /* w/e */ ];// array containing objects
var f = function ( item ) { /* w/e */ };// a function that takes an
item from array as argument and returns something else

Let's say you want to sort items of array by their image by f. You
could do this:

var sortedArray = array.sort( function ( a, b ) {
    return compare( f( a ), f( b ) );
} );

But then, you would call several times f on the exact same item, so
it's not good for perfs. So you would write this:

var comparisons = [ ];
array.map( f ).sort( function ( a, b ) {
    var comparison = compare( a, b );
    comparisons.push( comparison );
    return comparison;
} );
var index = 0;
var sortedArray = array.sort( function ( a, b ) {
    return comparisons[ i++ ];
} );

It would produce the same result but probably faster. And what I would
like is to be able to do this:

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


More information about the es-discuss mailing list