Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,181 questions

56,073 answers

573 users

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

3 answers 193 views
1 answer 159 views
1 answer 123 views
1 answer 134 views
1 answer 143 views
...