<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js'></script>
var fruits = [
{name:"banana", amount: 2},
{name:"apple", amount: 4},
{name:"pineapple", amount: 2},
{name:"mango", amount: 1}
];
sortBy = (key) => {
return (a, b) => (a[key] > b[key]) ? 1 : ((b[key] > a[key]) ? -1 : 0);
};
_.orderBy(fruits, ['name'],['asc']);
fruits.concat().sort(sortBy("name"));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash orderby | |
native sort |
Test name | Executions per second |
---|---|
lodash orderby | 1606761.8 Ops/sec |
native sort | 4931580.0 Ops/sec |
The provided JSON benchmark compares two different sorting approaches using a dataset of fruit objects defined in the preparation code. The options being tested are:
_.orderBy
Methodsort
Method1. Lodash's _.orderBy
Method
_.orderBy
function allows sorting of an array of objects based on specified properties and their order (ascending or descending). It handles the sorting in a way that is optimized for legibility and ease of use, abstracting away the complexity of custom sorting functions.2. Native JavaScript sort
Method
sort
method is a built-in array method that sorts the elements of an array in place and returns the sorted array. In this case, a custom comparison function (sortBy
) is defined to handle sorting based on a key (in this case, the name
attribute of the fruit objects). The comparison function compares two elements and returns a value indicating their relative positioning.Based on the latest benchmark results:
Lodash _.orderBy
Pros:
Cons:
Native Sort
Pros:
Cons:
_.orderBy
method.Use Cases: Choose Lodash for ease of use and scenarios involving complex data manipulations or where readability is paramount. Prefer native sort for performance-sensitive applications or when avoiding external dependencies.
Alternatives: Other alternatives for sorting in JavaScript include:
Ultimately, the choice between Lodash and native methods for sorting will depend on the specific requirements of the project, such as performance needs, code simplicity, and maintainability.