EN
JavaScript - sort array of objects by property value using Lodash
0
points
In this article, we would like to show you how to sort an array of objects by property value using the Lodash library in JavaScript.
1. Using orderBy() method
In this example, we use _.orderBy() method to sort array of objects by name property value in ascending order. The method takes three arguments: the array we want to sort, property name and order (ascending by default).
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
</head>
<body>
<script>
var array = [
{ id: 1, name: 'b' },
{ id: 2, name: 'a' }
];
array = _.orderBy(array, ['name'], ['asc']); // 'asc' - ascending / 'desc' - descending order
console.log(JSON.stringify(array , null, 4));
</script>
</body>
</html>
2. Using sortBy() method
In this example, we use _.sortBy() method to sort array of objects by name property value in ascending order.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
</head>
<body>
<script>
var array = [
{ id: 1, name: 'b' },
{ id: 2, name: 'a' }
];
array = _.sortBy(array, object => object.name);
console.log(JSON.stringify(array, null, 4));
</script>
</body>
</html>