javascript-lodashHow can I use Lodash to sort an array of objects by key value in JavaScript?
Using Lodash, you can sort an array of objects by key value in JavaScript by using the _.sortBy()
method. This method takes an array and a sorting function as its arguments. The sorting function should take an object as its argument and return the value to sort by.
For example:
let arr = [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 18 },
{ name: 'Bob', age: 22 }
];
let sorted = _.sortBy(arr, o => o.age);
console.log(sorted);
Output example
[
{ name: 'Jane', age: 18 },
{ name: 'John', age: 20 },
{ name: 'Bob', age: 22 }
]
The _.sortBy()
method takes an array, arr
, and a sorting function as its arguments. The sorting function, o => o.age
, takes an object, o
, as its argument and returns the value to sort by, o.age
. The sorted array is then stored in the sorted
variable. The output of the code is an array of objects sorted by age.
Helpful links
More of Javascript Lodash
- How do I use Lodash in a JavaScript playground?
- How can I use Lodash's reject function in JavaScript?
- How do I use Lodash to zip two JavaScript arrays together?
- How can I use Lodash's xor function to manipulate JavaScript objects?
- How can I check for undefined values in JavaScript using Lodash?
- How do I use yarn to install and use lodash in a JavaScript project?
- How can I use Lodash to create a hashmap in Javascript?
- How can I use Lodash's uniq() function to remove duplicate values from a JavaScript array?
- How can I use Lodash's throttle function in JavaScript?
- How can I use Lodash to remove empty properties from an object in JavaScript?
See more codes...