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

其他回答

// 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

谢谢你在这里找到的答案,我希望它能对别人有用。 这个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

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

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

console.log(objMax)

ES6解决方案

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

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

const getMaxFromListByField = (list, field) => { 
    return list[list.map(it => it[field]).indexOf(Math.max(...list.map(it => it[field])))] 
}