javascript-lodashHow do I use Lodash to sort an array of objects by a specific key in JavaScript?
Using Lodash to sort an array of objects by a specific key in JavaScript is a simple task.
var _ = require('lodash');
var array = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Mike', age: 35 },
];
var sortedArray = _.sortBy(array, 'age');
console.log(sortedArray);
Output example
[
{ name: 'Jane', age: 25 },
{ name: 'John', age: 30 },
{ name: 'Mike', age: 35 }
]
The code above uses the Lodash sortBy
method to sort an array of objects by the age
key. The sortBy
method takes two arguments: the array to be sorted and the key by which the array should be sorted. The array is then sorted in ascending order according to the value of the specified key.
Code explanation
var _ = require('lodash');
- imports the Lodash libraryvar array = [ ... ]
- array of objects to be sortedvar sortedArray = _.sortBy(array, 'age');
- uses the LodashsortBy
method to sort the array according to theage
keyconsole.log(sortedArray);
- prints the sorted array to the console
Helpful links
More of Javascript Lodash
- How do I use yarn to install and use lodash in a JavaScript project?
- How can I use Lodash to find the unique key of a JavaScript object?
- How do lodash and JavaScript differ in terms of usage in software development?
- How do I use Lodash to zip two JavaScript arrays together?
- How do I use Lodash in a JavaScript playground?
- How can I use Lodash's xor function to manipulate JavaScript objects?
- How do I use an online JavaScript compiler with Lodash?
- How can I use Lodash to manipulate JavaScript objects online?
- How do I use Lodash in JavaScript?
- How can I use lodash in a JavaScript sandbox?
See more codes...