Reputation: 15908
I would like to sort an array with a comparator like:
function myCustomComparator(a, b){...}
It would be like
var sorted = myArray.sort(myCustomComparator);
But I would like to use it inside a lodash command chain using sortBy
How can i use myCustomComparator
in a Lodash SortBy call?
Upvotes: 3
Views: 1259
Reputation: 102
From the Lodash documentation, it states:
Creates an array of elements, sorted in ascending order by the results of running each element in a collection thru each iteratee.
If anyone can prove me wrong otherwise, I don't think you're able to apply a custom comparator to lodashs' sortBy function.
If it helps, or for anyone stumbling on this, a custom comparator sort function can be achieved with the following snippet.
var arr = [ 4, 2, 1, 3, 5, 8, 7, 6, 0 ];
function customComparator(a, b) {
return (a > b) ? -1 : 1;
}
var sorted = arr.sort(customComparator);
Upvotes: 5