Saturday, September 6, 2025
HomeLanguagesJavascriptLodash _.best() Method

Lodash _.best() Method

The Lodash _.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:

  • array: The given array from which the best value is calculated.
  • function: The function which contains the condition for the best matching value.

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

Note: This will not work in normal JavaScript because it requires the lodash contrib library to be installed. 

Module Installation: Lodash contrib library can be installed using the following command:

npm install lodash-contrib –save

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




// Defining lodash contrib variable 
var _ = require('lodash-contrib'); 
  
// Array
var array = [11, 2, 43, 14, 12];
  
// Getting best value using best() method
var 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 lodash contrib variable 
var _ = require('lodash-contrib'); 
  
// Array
var array = [11, 2, 43, 14, 12];
  
// Getting best value using best() method
var 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 lodash contrib variable 
var _ = require('lodash-contrib'); 
  
// Array
var array = [11, 2, 43, 14, 12];
  
// Getting best value using best() method
var 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
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
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS