How to pick a random value from a map in Node.js

2 Answers

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

 



answered Jul 17, 2025 by avibootz
0 votes
function getRandomValue(inputMap) {
    /*
    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 = [...inputMap.values()];
 
    return values[~~(Math.random() * values.length)]
}
 
// Initialize the map
const myMap = new Map([
    [1, "C++"],
    [2, "C"],
    [3, "Java"],
    [4, "C#"],
    [5, "Rust"],
    [6, "Node.js"],
    [7, "Python"]
]);
 
const randomValue = getRandomValue(myMap);
console.log("Random value:", randomValue);
 
  
/*
run:
  
Random value: Rust
  
*/

 



answered Jul 17, 2025 by avibootz

Related questions

2 answers 127 views
1 answer 85 views
1 answer 94 views
1 answer 91 views
1 answer 115 views
2 answers 114 views
2 answers 123 views
...