Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
968 views
in Technique[技术] by (71.8m points)

arrays - Get object keys with the highest value in Javascript

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...