简体   繁体   中英

How can I get the largest number value along with the username from this array?

Im trying to get the user & value with the highest number from this array but have had no luck in my searches. I'm starting to wonder if my array is poorly written.

{
  "radtech2": 1,
  "conorlarkin4": 25,
  "jdon2001": 15,
  "nobel_veo": 101,
  "frapoden": 1,
  "duckyboy17": 31,
  "faeded": 30,
  "jimbob20001": 17,
  "leb0wski": 15,
  "3cavalry": 2,
  "hardoak22": 25,
  "deep_slide": 10000,
  "sillywil": 7
}

 const users = { "radtech2": 1, "conorlarkin4": 25, "jdon2001": 15, "nobel_veo": 101, "frapoden": 1, "duckyboy17": 31, "faeded": 30, "jimbob20001": 17, "leb0wski": 15, "3cavalry": 2, "hardoak22": 25, "deep_slide": 10000, "sillywil": 7 }; const highestUser = users => Object.keys(users).reduce( (highest, current) => highest.val > users[current] ? highest : { user: current, val: users[current] }, { user: undefined, val: -Infinity } ).user; console.log(highestUser(users));

Let me try to squeeze it into a one-liner approach using Object.keys() and Array.reduce() .

 const users = { "radtech2": 1, "conorlarkin4": 25, "jdon2001": 15, "nobel_veo": 101, "frapoden": 1, "duckyboy17": 31, "faeded": 30, "jimbob20001": 17, "leb0wski": 15, "3cavalry": 2, "hardoak22": 25, "deep_slide": 10000, "sillywil": 7 }; const res = Object.keys(users).reduce((a, b) => users[a] > users[b] ? a : b); console.log(res);

How the above code works is that I get the array of keys from the users object, and I use reduce to get the highest possible value and return the corresponding property from the array obtained from Object.keys().

Use keys() and entries() methods to search your JSON object. Save largest value into eg const largest and then find out which key belongs to this value.

What you show in your question is an Object , not an Array ; however, it does need to be turned into an array in order to work with it.

You can do that with Object.entries() , which will return an array of all the key/value pairs in the object.

Then you can use Array.reduce() to extract the one with the largest value.

 const data = { "radtech2": 1, "conorlarkin4": 25, "jdon2001": 15, "nobel_veo": 101, "frapoden": 1, "duckyboy17": 31, "faeded": 30, "jimbob20001": 17, "leb0wski": 15, "3cavalry": 2, "hardoak22": 25, "deep_slide": 10000, "sillywil": 7 } let winner = Object.entries(data).reduce((a, b) => (a[1] > b[1]) ? a : b) console.log(winner)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM