我正在寻找一个非常快速,干净和有效的方法来获得以下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。


当前回答

又快又脏:

Object.defineProperty (Array.prototype“分钟”, { 价值:函数(f) { F = F || (v => v); 返回。Reduce ((a, b) => (f(a) < f(b)) ?A: b); } }); Object.defineProperty (Array.prototype‘麦克斯’, { 价值:函数(f) { F = F || (v => v); 返回。Reduce ((a, b) => (f(a) > f(b)) ?A: b); } }); console.log ([1, 2, 3] .max ()); console.log([1, 2, 3]。Max (x => x*(4-x))); console.log ([1, 2, 3] .min ()); console.log([1, 2, 3]。Min (x => x*(4-x)));

其他回答

干净简单的ES6 (Babel)

const maxValueOfY = Math.max(...arrayToSearchIn.map(o => o.y), 0);

如果arrayToSearchIn为空,第二个参数应该确保有一个默认值。

// Here is very simple way to go:

// Your DataSet.

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

// 1. First create Array, containing all the value of Y
let result = numberArray.map((y) => y)
console.log(result) // >> [0.026572007,0.025057454,0.024530916,0.031004457]

// 2.
let maxValue = Math.max.apply(null, result)
console.log(maxValue) // >> 0.031004457

或者一个简单的排序!保持真实:)

array.sort((a,b)=>a.y<b.y)[0].y

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

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

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

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

或者在更现代的JavaScript中:

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