sortBy

sortBy(iterator[, context]) -> Array

Provides a custom-sorted view of the elements based on the criteria computed, for each element, by the iterator.

Elements of equivalent criterion value are left in existing order. Computed criteria must have well-defined strict weak ordering semantics (i.e. the < operator must exist between any two criteria).

Note that arrays already feature a native sort method, which relies on natural ordering of the array's elements (i.e. the semantics of the < operator when applied to two such elements). You should use sortBy only whe natural ordering is nonexistent or otherwise unsatisfactory.

The optional context parameter is what the iterator function will be bound to. If used, the this keyword inside the iterator will point to the object given by the argument.

Examples


['hello', 'world', 'this', 'is', 'nice'].sortBy(function(s) { return s.length; })
// -> 'is', 'this', 'nice', 'hello', 'world']

['hello', 'world', 'this', 'is', 'cool'].sortBy(function(s) {
  var md = s.match(/[aeiouy]/g);
  return null == md ? 0 : md.length;
})
// -> [ 'world', 'this', 'is', 'hello', 'cool'] (sorted by vowel count)