3

Imagine an object like this:

var values = {
    "2": 1,
    "53": 2,
    "56": 4,
    "57": 9,
    "61": 2,
    "62": 16,
    "63": 2,
    "398": 24,
    ...
}

My goal is, to find the 10 object keys, which have the highest value. In this case: 398, then 62 and so on (= [398, 62, ...]). I know how I can put this into an array, don't know how to receive the property key though.

Important: I can't change the format because it's a server response.

I tried with a for (key in values) {} loop but have no idea how to move on. This similar question and it's answer couldn't really help me either.

Community
  • 1
  • 1
sandrooco
  • 8,016
  • 9
  • 48
  • 86

4 Answers4

7

As commented before:

  • Create an array of keys: Object.keys(object)
  • Sort this array based on value: sort((a,b)=> object[b] - object[a])
  • Get necessary values: keys.slice(0,n)

var value = {2:1,53:2,56:4,57:9,61:2,62:16,63:2,398:24};

function getKeysWithHighestValue(o, n){
  var keys = Object.keys(o);
  keys.sort(function(a,b){
    return o[b] - o[a];
  })
  console.log(keys);
  return keys.slice(0,n);
}

console.log(getKeysWithHighestValue(value, 4))
Rajesh
  • 24,354
  • 5
  • 48
  • 79
3

You could sort by the values property and slice the result.

var values = { 2: 1, 53: 2, 56: 4, 57: 9, 61: 2, 62: 16, 63: 2, 398: 24 },
    result = Object
        .keys(values)
        .sort(function (a, b) { return values[b] - values[a]; })
        .slice(0, 10)
        .map(Number);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can use Object.keys to get key values

var value = {
"2": 1,
"53": 2,
"56": 4,
"57": 9,
"61": 2,
"62": 16,
"63": 2,
"398": 24,
}
var parsedKeys = Object.keys(value).map(x => parseInt(x));
var sortedKeys = parsedKeys.sort(function (a, b) {  return b - a;  });

Now you can get highest top 10 keys by sortedKeys.slice(0, 10);

Vikramaditya
  • 5,444
  • 6
  • 34
  • 45
  • What if I have array of words with count ? ex:- `[ { "text":"hello", "size":10},{ "text":"world", "size":2} ,....]` same to 100 object and find top 10 text and store it in an array ? – NoobCoder Jul 23 '20 at 18:40
  • See the example given [here](https://lodash.com/docs/4.17.15#sortBy) – Vikramaditya Jul 25 '20 at 09:40
-1

var value = {
    "2": 1,
    "53": 2,
    "56": 4,
    "57": 9,
    "61": 2,
    "62": 16,
    "63": 2,
    "398": 24
};

var sortable = [];
for (var key in value) {
    sortable.push([key, value[key]]);
}

sortable.sort(function(a, b) {
    return b[1] - a[1];
});

var result = [];
sortable.forEach(function(a) {
  result.push(a[0]);
});

console.log(result.slice(0, 10));
Đào Minh Hạt
  • 2,742
  • 16
  • 20