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


当前回答

干净简单的ES6 (Babel)

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

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

其他回答

求数组中所有对象的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)

ES6解决方案

Math.max(…array.map(函数(o){返回o.y;}))

详情见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

谢谢你在这里找到的答案,我希望它能对别人有用。 这个typescript函数可以被调用来搜索数组对象字段中可能存在的最大值:

function getHighestField(objArray: any[], fieldName: string) {
  return Number(
    Math.max.apply(
      Math,
      objArray?.map(o => o[fieldName] || 0),
    ) || 0,
  );
}

以这些值为例:

const scoreBoard = [
  { name: 'player1', score: 4 },
  { name: 'player2', score: 9 },
  { name: 'player3', score: 7 }
]

你可以这样调用这个函数:

const myHighestVariable = `This is the highest: ${getHighestField(scoreBoard, "score")}`;

结果会是这样的:

console.log(myHighestVariable);

这是最高的:9

注意null和空以及属性不在数组和空数组中

if ((value && value.length > 0)) {
  var maxObj = (value && value.length > 0) value.reduce(function (prev, current) {
    return ((parseInt(prev["y"]) || 0) > (parseInt(current["y"]) || 0)) ? prev : current
  })
}
{
  // else logic here
}