0

I'd like to calculate the highest number of "probs" , and get the highest number of "labels" with JavaScript or jQuery.

Down below, for example, "tulips."

I'd appreciate your help.

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
  }
]
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
이보성
  • 39
  • 5

2 Answers2

1

use 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,  )
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
1

Solution


Here is a clean ES6 way of doing this I belive this is the way to do this with the least amount of code but there are many ways to this

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)

Other ways to do this


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)
Fletcher Rippon
  • 1,837
  • 16
  • 21