Underscore.js _.comparator() Method

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 ]
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!



