Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use lodash sortBy together with custom order comparator

Tags:

lodash

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?

like image 812
Daniel Santos Avatar asked Dec 29 '25 09:12

Daniel Santos


1 Answers

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);
like image 56
wesleyfung Avatar answered Jan 01 '26 12:01

wesleyfung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!