首页 > 解决方案 > 我们如何获得 JSON 数组中的最大数字?

问题描述

我想计算最大数量的“probs”,并使用 JavaScript 或 jQuery 获得最大数量的“标签”。

例如,在下面,“郁金香”。

我会很感激你的帮助。

result_predictions=[
  {
    "label": "roses",
    "prob": 0.0056262025609612465
  },
  {
    "label": "daisy",
    "prob": 0.005660845898091793
  },
  {
    "label": "dandelion",
    "prob": 0.005297524854540825
  },
  {
    "label": "tulips",   // What I want to pick
    "prob": 0.9730507731437683  //the highest number
  },
  {
    "label": "sunflowers",
    "prob": 0.010364603251218796
  }
]

标签: javascriptjqueryjson

解决方案


使用Array.prototype.reduce()

const result_predictions = 
      [ { label: "roses",      prob: 0.0056262025609612465 } 
      , { label: "daisy",      prob: 0.005660845898091793  } 
      , { label: "dandelion",  prob: 0.005297524854540825  } 
      , { label: "tulips",     prob: 0.9730507731437683    } 
      , { label: "sunflowers", prob: 0.010364603251218796  } 
      ] 
       

const label_ofMax = result_predictions
                     .reduce((a,c)=>(a.prob<c.prob)?c:a)
                     .label

console.log( label_ofMax,  )


推荐阅读