Languages
[Edit]
EN

JavaScript - sort array of objects by property value using Lodash

0 points
Created by:
Eshaal-Wilkinson
774

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>

 

References

  1. Lodash Documentation - orderBy()
  2. Lodash Documentation - sortBy()

Alternative titles

  1. JavaScript - use Lodash library to sort array of objects by property value
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join