Finding the max value of an attribute in an array of objects

前端 未结 13 2097
不思量自难忘°
不思量自难忘° 2020-11-22 08:05

I\'m looking for a really quick, clean and efficient way to get the max \"y\" value in the following JSON slice:

[
  {
    \"x\": \"8/11/2009\",
    \"y\": 0         


        
相关标签:
13条回答
  • 2020-11-22 08:44

    Comparison of tree ONELINERS which handle minus numbers case (input in a array):

    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)
    

    editable example here. Ideas from: maxA, maxB and maxC (side effect of maxB is that array a is changed because sort is in-place).

    var a = [
      {"x":"8/11/2009","y":0.026572007},{"x":"8/12/2009","y":0.025057454},    
      {"x":"8/14/2009","y":0.031004457},{"x":"8/13/2009","y":0.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;
    
    document.body.innerHTML=`<pre>maxA: ${maxA}\nmaxB: ${maxB}\nmaxC: ${maxC}</pre>`;

    For bigger arrays the Math.max... will throw exception: Maximum call stack size exceeded (Chrome 76.0.3809, Safari 12.1.2, date 2019-09-13)

    let a = Array(400*400).fill({"x": "8/11/2009", "y": 0.026572007 }); 
    
    // Exception: Maximum call stack size exceeded
    
    try {
      let max1= Math.max.apply(Math, a.map(o => o.y));
    } catch(e) { console.error('Math.max.apply:', e.message) }
    
    try {
      let max2= Math.max(...a.map(o=>o.y));
    } catch(e) { console.error('Math.max-map:', e.message) }

    Benchmark for the 4 element array

    0 讨论(0)
提交回复
热议问题