javascript Finding the max value of a property in an array of objects

找出陣列中最大值, 這個和 Create An Array Of Unique Values In JavaScript 解法很像.

I’m looking for a really quick, clean and efficient way to get the max “y” value in the following JSON slice:

[
  {
    "x": "8/11/2009",
    "y": 0.026572007
  },
  {
    "x": "8/12/2009",
    "y": 0.025057454
  },
  {
    "x": "8/13/2009",
    "y": 0.024530916
  },
  {
    "x": "8/14/2009",
    "y": 0.031004457
  }
]

To find the maximum y value of the objects in array:

Math.max.apply(Math, array.map(function(o) { return o.y; }))

or in more modern JavaScript:

Math.max(...array.map(o => o.y))

Math.max()
The Math.max() static method returns the largest of the numbers given as input parameters, or -Infinity if there are no parameters.

console.log(Math.max(1, 3, 2));
// Expected output: 3

console.log(Math.max(-1, -3, -2));
// Expected output: -1

const array1 = [1, 3, 2];

console.log(Math.max(...array1));
// Expected output: 3

資料來源:
https://stackoverflow.com/questions/4020796/finding-the-max-value-of-a-property-in-an-array-of-objects

類似解法:
https://stackoverflow.max-everyday.com/2024/03/create-an-array-of-unique-values-in-javascript/

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *