Lodash _.comparator() Method

The Lodash _.comparator() method takes a binary predicate-like function and returns a comparator function which can be used as a callback for _.sort() method etc.
Syntax:
_.comparator( function );
Parameters: This method accepts a single parameter as listed above and discussed below.
- function: It is a predicate like defined function.
Return Value: This method returns a comparator function.
Note: To execute the below examples, you have to install the lodash-contrib library by using this command prompt and execute the following command.
npm install lodash-contrib
Below examples illustrate the Lodash _.comparator() method in JavaScript:
Example 1: Sorting using a comparator function.
Javascript
// Defining lodash contrib variable var _ = require('lodash-contrib');   var gfgFun = function(x, y) {     // Returns -1, 0 or 1     return x <= y; };   // Array var arr = [4, 8, 2, 9, 1];   var comp = _.comparator(gfgFun); // Using comparator function with _.sort() method arr.sort(comp);   console.log("Sorted Array :",arr) |
Output:
Sorted Array : [ 1, 2, 4, 8, 9 ]
Example 2: Reverse Sorting using a comparator function.
Javascript
// Defining lodash contrib variable var _ = require('lodash-contrib');   var gfgFun = function(x, y) {     // Returns -1, 0 or 1     return x >= y; };   // Array var arr = [1, 10, 2, 9, 1];   var comp = _.comparator(gfgFun); // Using comparator function with _.sort() method arr.sort(comp);   console.log("Sorted Array :",arr) |
Output:
Sorted Array : [ 10, 9, 2, 1, 1 ]
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!



