Array#sort(prop)

Peter van der Zee ecma at qfox.nl
Sun Apr 1 14:49:29 PDT 2012


No idea whether this has been discussed before, but I find myself
continuously doing this when sorting arrays with objects:

arr.sort(function(a,b){ if (a.prop < b.prop) return -1; if (a.prop >
b.prop) return 1; return 0; });

Couldn't we add an optional string argument to Array#sort that does
this for us? If supplied do the above, otherwise behave as usual. If
there's already a first arg planned for .sort (I haven't kept up),
make it the second arg.

arr.sort('prop');
=>
arr.sort(function(a,b){ if (a[prop] < b[prop]) return -1; if (a[prop]
> b[prop]) return 1; return 0; });

- peter


More information about the es-discuss mailing list