Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Js

Idiom #250 Pick a random value from a map

Choose a value x from map m.
m must not be empty. Ignore the keys.

// Objects
const values = Object.values(m);

// Maps
const values = [...m.values()];

const x = values[~~(Math.random() * values.length)]

This converts the values of m into an array first, because you cannot get a random element from an object or a map.
var arr = m.Values.ToArray();
var x = arr[Random.Shared.NextInt64(0, arr.Length)];

New implementation...
< >
programming-idioms.org