How to pick a random value from a map in TypeScript

2 Answers

0 votes
function getRandomValue(inputMap: Map<number, string>): string {
    const values: string[] = Array.from(inputMap.values());
     
    const randomIndex: number = Math.floor(Math.random() * values.length);
     
    return values[randomIndex];
}
 
// Initialize the map
const myMap: Map<number, string> = new Map([
    [1, "C++"],
    [2, "C"],
    [3, "Java"],
    [4, "C#"],
    [5, "Rust"],
    [6, "TypeScript"],
    [7, "Python"]
]);
 
const randomValue: string = getRandomValue(myMap);
console.log("Random value:", randomValue);
 
 
 
/*
run:
 
"Random value:",  "C#" 
 
*/

 



answered Jul 17, 2025 by avibootz
0 votes
function getRandomValue(inputMap: Map<number, string>): string {
    /*
    Math.random() generates a decimal from 0 up to (but not including) 1.
 
    Multiplying by values.length scales that number up to a valid index range.
 
    ~~ is a JavaScript trick: it double bitwise-negates the number, 
       which effectively truncates the decimal part—like Math.floor().
    */
    const values: string[] = [...inputMap.values()];
 
    return values[~~(Math.random() * values.length)]
}
 
  
// Initialize the map
const myMap: Map<number, string> = new Map([
    [1, "C++"],
    [2, "C"],
    [3, "Java"],
    [4, "C#"],
    [5, "Rust"],
    [6, "TypeScript"],
    [7, "Python"]
]);
  
const randomValue: string = getRandomValue(myMap);
console.log("Random value:", randomValue);

 
 
/*
run:
 
"Random value:",  "Java" 
 
*/

 



answered Jul 17, 2025 by avibootz

Related questions

...