How to pick a random value from a map in JavaScript

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, "JavaScript"],
    [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, "JavaScript"],
    [7, "Python"]
]);

const randomValue = getRandomValue(myMap);
console.log("Random value:", randomValue);

 
/*
run:
 
Random value: Python
 
*/

 



answered Jul 17, 2025 by avibootz

Related questions

...