<script>https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.js</script>
var arr = [
{name: "test", age: 20},
{name: "best", age: 30},
{name: "blah", age: 50},
{name: "js", age: 10},
{name: "style", age: 29},
];
_.sortBy(arr, 'age');
const sortBy = function(key){
return (a,b)=> (a[key]>b[key]) ? 1 : (b[key]>a[key]) ? -1 : 0;
};
arr.sort(sortBy('age'));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Native |
Test name | Executions per second |
---|---|
Lodash | 614297.4 Ops/sec |
Native | 2632827.2 Ops/sec |
Let's break down the benchmark and explain what is being tested.
The benchmark is comparing two approaches to sorting an array of objects in JavaScript: using Lodash's sortBy
function versus implementing a custom sorting function from scratch.
Lodash's sortBy
Function
sortBy
that allows you to sort arrays of objects based on a specific key.sortBy
function takes two arguments: the array of objects and the key to sort by. It uses a stable sorting algorithm (usually Timsort or Merge Sort) under the hood, which means it maintains the relative order of equal elements.Custom Sorting Function
a
and b
, which are the two elements to compare. It returns a negative value if a
is less than b
, zero if they are equal, or a positive value if a
is greater than b
. This is known as a "strict" comparison.Pros and Cons
sortBy
FunctionOther Considerations
Library and Special JS Feature
There are no specific libraries or special JavaScript features used in this benchmark beyond what's standard for both approaches (i.e., array sorting).
Alternative Approaches
Some alternative approaches to sorting arrays of objects include:
Array.prototype.sort()
with a custom compare functionHowever, the question is specifically asking about comparing _.sortBy
from Lodash and native sorting functions.
In summary, this benchmark compares two approaches to sorting arrays of objects in JavaScript: using Lodash's sortBy
function versus implementing a custom sorting function from scratch.