Determining the highest value of a key in an object array

I need a simple and efficient method to find the maximum 'y' value in this array of objects:

[   {     "x": "10/11/2021",     "y": 0.019834729   },   {     "x": "10/12/2021",     "y": 0.021934728   },   {     "x": "10/13/2021",     "y": 0.018274834   },   {     "x": "10/14/2021",     "y": 0.022387492   } ] 

Can Math.max be utilized here instead of a for-loop?

To find the maximum ‘y’ value in an array of objects efficiently, you can indeed use Math.max along with map to streamline the process. This avoids manual looping and ensures simplicity.

Here’s a quick and effective way to achieve this:

const data = [
  { "x": "10/11/2021", "y": 0.019834729 },
  { "x": "10/12/2021", "y": 0.021934728 },
  { "x": "10/13/2021", "y": 0.018274834 },
  { "x": "10/14/2021", "y": 0.022387492 }
];

const maxY = Math.max(...data.map(item => item.y));

console.log('Maximum y value is:', maxY);

This solution is straightforward:

  1. Use map to create an array of ‘y’ values.
  2. Apply Math.max with the spread operator to find the highest value.

The result is efficient and easy to maintain.