score:3

Accepted answer

You can sort() the keys by their associated count value and slice() the result:

let data = {
    "entity": {
      "element1": 1,
      "element2": 2,
      "element3": 3,
      "element4": 4,
      "element5": 5,
      "element6": 6,
      "element7": 7
    }
  },

  mymap = data.entity;


let elements = Object.keys(mymap)
  .sort((a, b) => mymap[b] - mymap[a])
  .slice(0, 5);

let counts = elements.map(key => mymap[key]);

console.log('5 highest counts', JSON.stringify(counts))
console.log('5 highest elements', JSON.stringify(elements))

score:0

You could use the angularJS $filter service to do the sorting and top n:

(function() {
  var app = angular.module("soDemo", []);
  app.controller("soDemoController", SoDemoController);

  SoDemoController.$inject = ['$scope', '$filter'];

  function SoDemoController($scope, $filter) {
    var vm = {
      counts: [{
          name: 'element1',
          count: 15
        },
        {
          name: 'element2',
          count: 26
        },
        {
          name: 'element3',
          count: 37
        },
        {
          name: 'element4',
          count: 45
        }
      ]
    };

    var limitToFilter = $filter('limitTo');
    vm.sortedCounts = limitToFilter($filter('orderBy')(vm.counts, '-count'), 3);
    $scope.vm = vm;
    return;
  }
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div class="sample" ng-app="soDemo" ng-controller="soDemoController">
  <h2>Counts</h2>
  <pre>{{vm.counts | json}}</pre>
  <h2>Sorted Counts (top 3)</h2>
  <pre>{{vm.sortedCounts | json}}</pre>
</div>

score:0

Object.keys an map.

const entity = {
  "element1": 99,
  "element2": 15,
  "element3": 26,
  "element4": 37,
  "element5": 45,
  "element6": 2
};

const result = Object.keys(entity).map(key => ({ key, value: entity[key] })).sort((elemA, elemB) => {
  if (elemA.value > elemB.value) {
    return -1;
  } else if (elemB.value > elemA.value) {
    return 1;
  }
  return 0;
}).slice(0, 5);
//
// [ { key: 'element1', value: 99 },
//   { key: 'element5', value: 45 },
//   { key: 'element4', value: 37 },
//   { key: 'element3', value: 26 },
//   { key: 'element2', value: 15 } ]
console.log(result);

Just add another map or reduce in the end get the result in desired format.


Related Query

More Query from same tag