The _.comparator() method takes a binary predicate-like function and returns a comparator function which can be used as a callback for the _.sort() method etc.
Syntax:
_.comparator( function );
Parameters:
- function: a predicate-like function defined.
Return Value: This method returns a comparator function.
Note: This will not work in normal JavaScript because it requires the underscore.js contrib library to be installed.
underscore.js contrib library can be installed using npm install underscore-contrib –save.
Example 1: Sorting using a comparator function.
javascript
// Defining underscore contrib variableconst _ = require('underscore-contrib');let gfgFun = function (x, y) { // Returns -1, 0 or 1 return x <= y;};// Arraylet arr = [4, 8, 2, 9, 1];let comp = _.comparator(gfgFun);// Using comparator function with _.sort() methodarr.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 underscore contrib variableconst _ = require('underscore-contrib');let gfgFun = function (x, y) { // Returns -1, 0 or 1 return x >= y;};// Arraylet arr = [4, 8, 2, 9, 1];let comp = _.comparator(gfgFun);// Using comparator function with _.sort() methodarr.sort(comp);console.log("Sorted Array :", arr) |
Output:
Sorted Array : [ 9, 8, 4, 2, 1 ]
