how to sort and select top 5 elements in a json array using angular JS

Viewed 3953

I have a REST API which returns a Java.util.HashMap object as JSON.

It has data in the form (some 15-20 elements like this):

"entity": {
    "element1": 15,
    "element2": 26,
    "element3": 37,
    "element4": 45
}

I am calling the API and getting this map in my Angular JS application as follows:

url = 'http://localhost:8080/dummy/';
console.log(url);
$http.get(url).success(function(data) {
    var elements = [];
    var counts = [];
    var mymap = data.entity;
    console.log(mymap);
    Object.keys(mymap).forEach(function(key) {
        elements.push(key);
        counts.push(mymap[key]);
    });
})

Next, I am using this to display it as a bar graph in the UI using high charts:

Highcharts.chart('hc-container', {
chart : {
    type : 'bar'
},
title : {
    text : 'Top 5 element count'
},
xAxis : {
    categories : elements
},
series : [ {
    name : 'count',
    data : counts
} ]
});

HTML:

<body ng-controller="myController">
  <div id="hc-container">Placeholder for chart</div>
</body>

Now currently it is showing all the elements from the map. I only need the top 5 elements with the highest counts to be displayed in the bar graph.

How can I do that?

3 Answers
Related