【问题标题】:How do we get the highest number in a JSON array? [closed]我们如何获得 JSON 数组中的最大数字? [关闭]
【发布时间】:2021-01-10 05:40:59
【问题描述】:
我想用 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
}
]
【问题讨论】:
标签:
javascript
jquery
json
【解决方案1】:
解决方案
这是一个干净的 ES6 方法,我相信这是用最少的代码做到这一点的方法,但有很多方法
sort
const results = [
{
"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 highest = results.sort((a, b) => b.prob - a.prob)[0].label
console.log(highest)
其他方法
map, Math.max & filter
const results = [
{
"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 probs = results.map(res => res.prob)
const highestProb = Math.max(...probs)
const result = results.filter(res => res.prob == highestProb)[0].label
console.log(result)
reduce
const results = [
{
"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 highest = results.reduce((a, b) => a.prob <= b.prob ? b : a).label
console.log(highest)
【解决方案2】:
使用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, )