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


当前回答

注意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
}

其他回答

首先,你应该解析JSON字符串,这样你就可以很容易地访问它的成员:

var arr = $.parseJSON(str);

使用map方法提取值:

arr = $.map(arr, function(o){ return o.y; });

然后你可以在max方法中使用数组:

var highest = Math.max.apply(this,arr);

或者作为一行语句:

var highest = Math.max.apply(this,$.map($.parseJSON(str), function(o){ return o.y; }));

非常简单

     const array1 = [
  {id: 1, val: 60},
  {id: 2, val: 2},
  {id: 3, val: 89},
  {id: 4, val: 78}
];
const array2 = [1,6,8,79,45,21,65,85,32,654];
const max = array1.reduce((acc, item) => acc = acc > item.val ? acc : item.val, 0);
const max2 = array2.reduce((acc, item) => acc = acc > item ? acc : item, 0);

console.log(max);
console.log(max2);

它返回对象简化的@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)

每个数组,并得到最大值与数学。

data.reduce((max, b) => Math.max(max, b.costo), data[0].costo);
// 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