我正在寻找一个非常快速,干净和有效的方法来获得以下JSON切片中的最大“y”值:

[
  {
    "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
  }
]

for循环是唯一的方法吗?我很喜欢用Math.max。


当前回答

var max = 0;                
jQuery.map(arr, function (obj) {
  if (obj.attr > max)
    max = obj.attr;
});

其他回答

求数组中所有对象的y的最大值:

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

或者在更现代的JavaScript中:

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

它返回对象简化的@andy polhill answare

var data = ( { y: 90 }, { y: 9 }, { y: 8 } ] Const Max = data。Reduce ((prev, current)=> ((prev, current))Y >电流。Y) ?当前),0)//返回对象 console.log (max)

let List= [{votes:4},{votes:8},{votes:7}]

let objMax = List.reduce((max, curren) => max.votes > curren.votes ? max : curren);

console.log(objMax)

以下是ES6的最短解决方案(One Liner):

Math.max(...values.map(o => o.y));

在对象数组中找到属性“Y”值最大的对象

一种方法是使用Array reduce..

const max = data.reduce(function(prev, current) {
    return (prev.y > current.y) ? prev : current
}) //returns object

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce http://caniuse.com/#search=reduce (IE9及以上版本)

如果你不需要支持IE(只支持Edge),或者可以使用预编译器,比如Babel,你可以使用更简洁的语法。

const max = data.reduce((prev, current) => (prev.y > current.y) ? prev : current)