sortBy source npm

_.sortBy(collection, [iteratees=[_.identity]])

Creates an array of elements, sorted in ascending order by the results of running each element in a collection through each iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements. The iteratees are invoked with one argument: (value).

Arguments

  1. collection (Array|Object)

    The collection to iterate over.

  2. [iteratees=[_.identity]] (...(Function|Function[]|Object|Object[]|string|string[])

    The iteratees to sort by, specified individually or in arrays.

Returns (Array)

Returns the new sorted array.

Example

var resolve = _.partial(_.map, _, _.values);

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 42 },
  { 'user': 'barney', 'age': 34 }
];

resolve( _.sortBy(users, function(o) { return o.user; }) );
// => // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]

resolve( _.sortBy(users, ['user', 'age']) );
// => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]

resolve( _.sortBy(users, 'user', function(o) {
  return Math.floor(o.age / 10);
}) );
// => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]