This post will discuss how to find the maximum and minimum object among the array of objects in JavaScript.

To find the maximum and minimum of custom objects, we need to define a criterion for comparing them, such as a specific property or a custom function. Here are some of the methods we can use:

1. Using Math.max() and Math.min() functions with apply() function

To find the maximum and minimum object among the array of objects, we need to compare the values of a specific property of the objects. There are different ways to do this, but one common function is to use the Math.max() and Math.min() functions, which return the maximum and minimum values among a list of arguments. However, these functions only work with numbers, not objects. To use them with objects, we need to use the apply() function, which allows us to call a function with a given this value and an array of arguments. We also need to use the map() function, which creates a new array with the results of calling a function on every element in an array. For instance:

Download  Run Code

2. Using Array.reduce() function

The Array.reduce() function executes a reducer function on each element of an array, resulting in a single output value. The reducer function takes four arguments: accumulator, current value, current index, and source array. The accumulator is the value that accumulates the result of the reducer function. The current value is the current element being processed in the array. The current index is the index of the current element in the array. The source array is the array that reduce() was called upon. We can use this function to compare each element in an array of objects and return the maximum or minimum object according to a criterion. For instance:

Download  Run Code

3. Using Lodash or Underscore.js library

This is a more convenient way to find the maximum and minimum of custom objects in JavaScript. Lodash and Underscore.js are popular libraries that provide various utility functions for working with arrays, objects, collections, and other data types. To use these libraries, we need to include them in our HTML file or import them in our JavaScript file. For instance:

To find the maximum and minimum of custom objects using Lodash or Underscore.js, we can use their maxBy() and minBy() functions. These functions take an array of objects and a criterion as arguments, and return the object with the maximum or minimum value of the criterion. The criterion can be a property name, a function, or an array of property names. For instance:

Download Code

 
We can find more information and examples about these functions in this web page for Lodash and this web page for Underscore.js.

That’s all about finding the maximum and minimum object among the array of objects in JavaScript.