Skip to content
Related Articles

Related Articles

Node.js lodash.sortBy() Function
  • Last Updated : 29 Jun, 2020

Lodash is a module in Node.js that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The Loadsh.sortBy() function is used to sort the array in ascending order.

Syntax:

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

Parameters: This parameter holds the collection as a first parameter, Second parameter is optional. The second parameter is basically a function that tells how to sort.

Return Value: It returns the sorted collection.

Note: Please install lodash module by npm install lodash before using the below given code.



Example 1:




let lodash = require("lodash");
let arr = [2, 1, 8, 4, 5, 8];
  
console.log("Before sorting: ", arr);
console.log("After sorting: ", lodash.sortBy(arr));

Output:

Example 2:




let lodash = require("lodash");
let arr = [2, 1, 5, 8, "a", "b", "10"];
  
console.log("Before sorting: \n" + arr);
console.log("After sorting: \n" 
        + lodash.sortBy(arr));

Output:

Example 3:




let lodash = require("lodash");
let arr = [
  {val:10, weight:100},
  {val:9, weight:150},
  {val:11, weight:10},
  {val:1, weight:1000},
  {val:74, weight:140},
  {val:7, weight:100},
];
  
console.log("sorted by val: \n"
  lodash.sortBy(arr, (e) => {
    return e.val
}));
  
console.log("sorted by weight: \n"
  lodash.sortBy(arr, (e) => {
    return e.weight
}));

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :