Skip to content

Instantly share code, notes, and snippets.

@vjeux
Forked from madrobby/LICENSE.txt
Created December 12, 2011 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vjeux/1466963 to your computer and use it in GitHub Desktop.
Save vjeux/1466963 to your computer and use it in GitHub Desktop.
Functional array sorting

This is a handy helper for functional sorting of arrays based on their content.

var sortBy = function(a,b){return a.slice().sort(function(c,d){return b(c)-b(d)})}

sortBy(['Fuchs','Diaz','Schmidt'], function(name){ return name.length })
// => ["Diaz", "Fuchs", "Schmidt"]

sortBy([1,2,3], Math.random)
// => [3,1,2]

It's an implementation of Ruby's Enumberable#sort_by functionality, see http://www.ruby-doc.org/core/classes/Enumerable.html#M001481 for more info.

A similiar implementation is available in Prototype.js, as Enumerables, see http://api.prototypejs.org/language/Enumerable/prototype/sortBy/.

function(
a, // array to sort (will not be altered)
b // sorting function
) {
return a
.slice() // create a clone of the array
.sort( // sort the array with JS' built-in sort function
function(d, e) {
return b(c) - b(d)
}
)
}
function(a,b,c){c=a.slice();return c.sort(function(d,e){d=b(d),e=b(e);return(d<e?-1:d>e?1:0)})};
Copyright (c) 2011 Christopher Chedeau, http://blog.vjeux.com/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
"name": "array_sort",
"description": "Functional sorting of arrays",
"keywords": [
"array",
"functional"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment