Skip to content
Advertisement

get 3 items with the highest values from JavaScript dictionary [closed]

i have something like dict = {"apple": 1, "orange":10,"watermelon":5, "banana":15} how i can get the 3 highest keys .

//output ["banana","orange", "watermelon"]

Advertisement

Answer

Use Object.entries and some destructuring to sort, slice the first 3 elements of the sorted entries array, then map to create the array of fruit names:

const dict = {"apple": 1, "orange":10,"watermelon":5, "banana":15};
const top3 = Object
  .entries(dict) // create Array of Arrays with [key, value]
  .sort(([, a],[, b]) => b-a) // sort by value, descending (b-a)
  .slice(0,3) // return only the first 3 elements of the intermediate result
  .map(([n])=> n); // and map that to an array with only the name

console.log(top3);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement