Open In App

Underscore.js _.best() Method

The _.best() method takes an array and a function and generates the best suitable value from that array using the conditions of the function.

Syntax:



_.best(array, function)

Parameters: This method accepts two parameters as mentioned above and described below:

Return Value: This method returns the best value from the array.



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

Example 1: In this example, we will get the best value as the greatest value from the array.




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [11, 2, 43, 14, 12];
// Getting best value using best() method
let best_val = _.best(array, function (x, y) {
    return x > y;
});
console.log("Array : ", array);
console.log("Best value : ", best_val);

Output:

Array :  [ 11, 2, 43, 14, 12 ]
Best value :  43

Example 2: In this example, we will get the best value as the smallest value from the array.




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [11, 2, 43, 14, 12];
// Getting best value using best() method
let best_val = _.best(array, function (x, y) {
    return x < y;
});
console.log("Array : ", array);
console.log("Best value : ", best_val);

Output:

Array :  [ 11, 2, 43, 14, 12 ]
Best value :  2

Example 3: In this example, we will get the best matching value as 12 from the array.




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [11, 2, 43, 14, 12];
// Getting best value using best() method
let best_val = _.best(array, function (x) {
    return x == 12;
});
console.log("Array : ", array);
console.log("Best value : ", best_val);

Output:

Array :  [ 11, 2, 43, 14, 12 ]
Best value :  12

Article Tags :