-4
data = {
"ImageDetails": [
    {
        "application": "unknownApp,
        "count": 107757,        
    },
    {
        "application": "app6",
        "count": 1900,
    },
    {
        "application": "app8",
        "count": 0,
    },
    {
        "application": "app3",
        "count": 100,
    },
    {
        "application": "app9"
        "count": 0,
    },
    {
        "application": "app1"
        "count": 0,
    },
    {     
        "application": "app10"
        "count": 0,
    },
    {
        "application": "app7",
        "count": 0,
    }
  ]
}

when i subscribed api i am getting data as above.

Output should return top 5 application name based on count property ImageDetails. expected Output : [unknownApp,app6,app3,app8,app9]

Anonymous
  • 1
  • 3
  • So you want to sort the data based on the count and get 5 with the most count? – kennarddh Jul 10 '23 at 04:56
  • Yes and i wants to return application names of highest individual count – Anonymous Jul 10 '23 at 05:10
  • Does this answer your question? [Sorting object property by values](https://stackoverflow.com/questions/1069666/sorting-object-property-by-values) – Shri Hari L Jul 10 '23 at 05:22
  • [Sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) based on the `count` value and [slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) first 5 items. Refer [this answer](https://stackoverflow.com/a/37607084/11566161) – Shri Hari L Jul 10 '23 at 05:23

1 Answers1

1

Your data is invalid but I fixed it by adding missing quotes and comma

But if the data from the api is malformed you probably have to ask the data provider

structuredClone is used to deep copy the array so when you modify the copied array the original won't be changed

You can sort the data based on the count then slice to get top 5

Then map the data to get only the app names

const apps = data.ImageDetails

const sortedApps = structuredClone(apps).sort((a, b) => {
  return b.count - a.count
})

const top5Apps = sortedApps.slice(0, 5)

const top5AppNames = top5Apps.map(app => app.application)

console.log(top5AppNames)
<script>
  // Data here to show the js code on top
  const data = {
    "ImageDetails": [{
        "application": "unknownApp",
        "count": 107757,
      },
      {
        "application": "app6",
        "count": 1900,
      },
      {
        "application": "app8",
        "count": 0,
      },
      {
        "application": "app3",
        "count": 100,
      },
      {
        "application": "app9",
        "count": 0,
      },
      {
        "application": "app1",
        "count": 0,
      },
      {
        "application": "app10",
        "count": 0,
      },
      {
        "application": "app7",
        "count": 0,
      }
    ]
  }
</script>
kennarddh
  • 2,186
  • 2
  • 6
  • 21