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

一种方法是使用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)

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

比较三个处理负号大小写的oneliner(在数组中输入):

var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y; // 30 chars time complexity:  O(n)

var maxB = a.sort((a,b)=>b.y-a.y)[0].y;    // 27 chars time complexity:  O(nlogn)
           
var maxC = Math.max(...a.map(o=>o.y));     // 26 chars time complexity: >O(2n)

这里是可编辑的示例。来自:maxA, maxB和maxC的想法(maxB的副作用是数组a被改变,因为排序是到位的)。

var a = [ {" x ": 8/11/2009”、“y”:026572007 {" x "}表示:“8/12/2009”、“y”:025057454} {" x ": 8/14/2009”、“y”:031004457 {" x "}表示:“8/13/2009”、“y”:024530916} ] var maxA = a.reduce((a,b)=>a.y>b.y?a:b) y; var maxC = Math.max(.. a.map(o=>o.y)); var maxB = a.sort((a,b)=>b.y-a.y)[0].y; 文件。身体。innerHTML = ' < pre - > maxA: $ {maxA} \ nmaxB: $ {maxB} nmaxC: $ {maxC} < / pre - > ';

对于较大的数组,Math.max…最大调用堆栈大小超过(Chrome 76.0.3809, Safari 12.1.2,日期2019-09-13)

let a =数组(400*400)。Fill ({"x": "8/11/2009", "y": 0.026572007}); // Exception:超过最大调用堆栈大小 尝试{ let max1= Math.max。apply(Math, a.p ap(o => o.y)); } catch(e) {console.error('Math.max. error ')应用:',e.message)} 尝试{ let max2= Math.max(…a.map(o=>o.y)); } catch(e) {console.error('Math. error ')Max-map:', e.message)}

4元素数组的基准测试

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

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

console.log(objMax)

非常简单

     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);