Lodash – sortBy method

  • Post author:
  • Post category:Lodash
  • Post comments:1 Comment
Lodash - sortBy method

Syntax Of Lodash sortBy method

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

Lodash sortBy method creates an array of elements, sorted in ascending order by the results of running each element in a collection thru 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

  • collection (Array|Object) − The collection to iterate over.
  • [iteratees=[_.identity]] (…(Function|Function[])) − The iteratees to sort by.

Output

  • (Array) − Returns the new sorted array.

Example

var _ = require('lodash');
var users = [
   { user: 'Joe', age: 48, active: false },
   { user: 'Robert', age: 34, active: true },
   { user: 'Julie', age: 40, active: false },
   { user: 'Stafey', age: 36, active: true }
];
var result = _.sortBy(users, [function(item) { return item.user; }]);
console.log(result);

var result = _.sortBy(users, ['user', 'age']);
console.log(result);

Save the above program in tester.js. Run the following command to execute this program.

Command

\>node tester.js

Output

[
   { user: 'Joe', age: 48, active: false },
   { user: 'Julie', age: 40, active: false },
   { user: 'Robert', age: 34, active: true },
   { user: 'Stafey', age: 36, active: true }
]
[
   { user: 'Joe', age: 48, active: false },
   { user: 'Julie', age: 40, active: false },
   { user: 'Robert', age: 34, active: true },
   { user: 'Stafey', age: 36, active: true }
]

Next Topic – Click Here

This Post Has One Comment

Leave a Reply