Underscore.js _.comparator() Method
Last Updated :
11 Apr, 2023
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
const _ = require( 'underscore-contrib' );
let gfgFun = function (x, y) {
return x <= y;
};
let arr = [4, 8, 2, 9, 1];
let comp = _.comparator(gfgFun);
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
const _ = require( 'underscore-contrib' );
let gfgFun = function (x, y) {
return x >= y;
};
let arr = [4, 8, 2, 9, 1];
let comp = _.comparator(gfgFun);
arr.sort(comp);
console.log( "Sorted Array :" , arr)
|
Output:
Sorted Array : [ 9, 8, 4, 2, 1 ]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...