Thursday, September 4, 2025
HomeLanguagesJavascriptUnderscore.js _.comparator() Method

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 variable
const _ = require('underscore-contrib');
 
let gfgFun = function (x, y) {
    // Returns -1, 0 or 1
    return x <= y;
};
 
// Array
let arr = [4, 8, 2, 9, 1];
 
let 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 underscore contrib variable
const _ = require('underscore-contrib');
 
let gfgFun = function (x, y) {
    // Returns -1, 0 or 1
    return x >= y;
};
 
// Array
let arr = [4, 8, 2, 9, 1];
 
let comp = _.comparator(gfgFun);
// Using comparator function with _.sort() method
arr.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, neveropen 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!
RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS