1

I need help with the following problem: How is it possible to extract a random value from the object below?

const hellos = {
English: "Hello",
Japanese: "Konnichiwa",
German: "Hallo",
Spanish: "Hola",
Arabic: "Ahlan wa sahlan",
Chinese: "Nihao",
};

random output in console to test. E.g. "konnichiawa", "hola", etc.

I couldn't write my code down, because it's still hard for me as a beginner in JS. Please kindly give me some tips. Thank you!

James Z
  • 12,209
  • 10
  • 24
  • 44

1 Answers1

1

Checkout https://stackoverflow.com/a/15106541/13583510 which picks a random key and return the value.
Since the key doesn't seem to be important as you haven't mentioned in your case you can choose a random value from the values array of the Object (Object.values(hellos)).
The answer in the link gives access to both the key and value so you can use it as well since retrieving a value from a given random key can be achieved in constant time.

const hellos = {English: "Hello",Japanese: "Konnichiwa",German: "Hallo",Spanish: "Hola",Arabic: "Ahlan wa sahlan",Chinese: "Nihao",};

var randomVal = function (obj) {
    var vals = Object.values(obj);
    return vals[ vals.length * Math.random() << 0];
};

console.log(randomVal(hellos))
cmgchess
  • 7,996
  • 37
  • 44
  • 62