0

I have a Javascript question.

var choices = {
    "red": {
        number: 1
    },
    "blue": {
        number: 2
    },
    "black": {
        number: 3
    },
    "green": {
        number: 4
    },
    "white": {
        number: 3
    }

How can we get the 2 keys of the dict "choices" with the least "number" ?

In this example it would be "red" and "blue". If there is a tie, I would like to have a random one between the tied one.

All my solutions are really ugly so I am asking for help.

rudy rhatal
  • 123
  • 4
  • You should look into [sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) and [Object.entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) – Sheraff Oct 12 '20 at 19:33
  • check [this ans](https://stackoverflow.com/questions/53248638/sort-nested-dictionary-by-value-in-js) – KashyapVadi Oct 12 '20 at 19:35
  • 1
    `Object.keys(choices).sort((a,b) => choices[a].number - choices[b].number).slice(0,2)` – adiga Oct 12 '20 at 19:50

0 Answers0