Picking a Random Item from an Array

by kirupa | 7 July 2012

Let's say you have an array called myShows that contains a list of some awesome TV shows that you like to watch:


This is a companion discussion topic for the original entry at http://www.kirupa.com/html5/picking_random_item_from_array.htm

Great tutorial but how would I do it if I want to receive 3 random shows?

One way would be to shuffle the array and then remove the first three items from it: http://www.kirupa.com/html5/shuffling_array_js.htm

That would be inefficient for large sets of data, so you could just literally remove three random items using something as follows:

var myShows = ['Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter'];

function getRandomIndex(items) {
  return Math.floor(Math.random() * items.length);
}

for (var i = 0; i < 3; i++) {
  var removedItem = myShows.splice(getRandomIndex(myShows), 1);
  document.writeln(removedItem)
}

Does this help? :smile:

Cheers,
Kirupa

Kirupa,

Thank you for the walk-thru. As a newb to JS, how do I run the script and can I package it in an executable as a stand-alone app for a friend to run it from their system? Also, I changed it to fit our needs, but I cannot see it working. Help?

var myElectives = ['Fishing', 'Playground', 'Bike Riding', 'Underwater Basket Weaving', 'Playing with the Teacher', 'Silent Reading', 'Going to the Library'] var lastItem = myElectives.Length - 1 var elective = myElectives[Math.floor(Math.random() * myElectives.length)];

JDS

Hi JDS! You will need to place your JS code inside a script tag in a HTML page. You can use the template here: https://www.kirupa.com/html5/html5_starting_template.htm

Now, are you planning on displaying the result to the screen? Or would a developer tool console work? The Console Logging tutorial can help with the second part: https://www.kirupa.com/html5/console.htm

For sharing with your friend, all you need to send is an HTML page. There is no need for an executable. Depending on what you answer for how you wish to display the result to the screen, I can help you further :slight_smile:

1 Like

Hey Kirupa,

Thank you for responding! I wrapped it in a script tag, but I have a feeling I’m missing a display of the var value.

What I’m going for is for the principal to press a button on the display to randomly select a class for a student. The elementary students are getting to select an elective class for fun. They get a list of options and and will choose their 1st, 2nd, and 3rd preferences. I need the script to take all their selections, group them, and randomly comprise a class list.

Using your suggestions, here is my

[code]

Stalker Elementary School - Elective Class Random Selector Elective Class Random Selector [/code]

JD Stewart

How do you want to display it? One quick and dirty way is by using an alert statement that will display something in a dialog:

var myElectives = ['Fishing', 'Playground', 'Bike Riding', 'Underwater Basket Weaving', 'Playing with the Teacher', 'Silent Reading', 'Going to the Library'];
var lastItem = myElectives.Length - 1;
var elective = myElectives[Math.floor(Math.random() * myElectives.length)];
alert(elective);

A better approach would be to display it on your page somewhere! This article can teach you the basics of what is involved there: https://www.kirupa.com/html5/modifying_dom_elements.htm (The entire section on the DOM (https://www.kirupa.com/javascript/learn_javascript.htm) . may be helpful if this is your first foray into this part of web development :slight_smile:

how can we do this same code in c?

let show = myShows[Math.floor(Math.random() * myShows.length)];

That is a tough one to answer here, for most of the people who post here are more webdev focused :stuck_out_tongue:

This is something you may want post on the C-related sections on stackoverflow.

Hey Kirupa,
Great work!!
I need to pick the random number from the array without repetition. As a newbie to JS I tried it but seems like I am missing something. Can you pls help me with it?

Thanks!

I’m sure @senocular or @krilnon will have a much better solution, but what I do is just shuffle the array first and then pick all the items in sequence. This ensures no items is picked up more than once.

This article can help:

:slight_smile:

Oh My God This is Incredibly Helpfull for me thanks… . I will be active on this site for learning JS one time again Thanks
:grin:

1 Like

Why do we have to use Square Brackets when using Math .floor and Math.random. For eg: ```
let value = myArray[Math.floor(Math.random() * myArray.length)];

thanks in advance

The square brackets are used to get an item from an array using an index number:

let foo = myArray[2]; // get the third item

Now what needs to be inside the bracket is a number. You can have any expression inside there that returns a number. The Math.floor and Math.random functions in the example are helping with getting back a number.

:grinning:

Hey, Kirupa! How are you doing?
Sorry to bother you, I have a question to something i been struggling with!
i want to create a “group” basically ^^
e.g.

channel.send('1')
await sleep(10000)
channel.send('2');
await sleep(10000)

which that would be “group 1” ^

channel.send('3')
await sleep(10000)
channel.send('4');
await sleep(10000)

which would be “group 2” ^

and these run randomly depending on what group the code picks

so i need to put them in functions and put the functions in an array and pick a random index
but been struggling doing that haha

could you help me out? thanks :slight_smile:

I can look at it later tonight :slight_smile:

Are you running in a Node environment?

Hey! :slight_smile:
Yes, I am running it in a Node environment, would that be an issue?
i could definitely change it if you want!

Not at all. I was just curious because I saw sleep, which is a much requested (but missing) feature in browser JS :clown_face:

Here is one way for you to randomly call one of the functions:

function groupOne() {
  channel.send('1')
  await sleep(10000)
  channel.send('2');
  await sleep(10000)
}

function groupTwo() {
  channel.send('3')
  await sleep(10000)
  channel.send('4');
  await sleep(10000)
}

let groups = ["one", "two"];
let group = groups[Math.floor(Math.random() * groups.length)];

if (group == "one") {
  groupOne();
} else {
  groupTwo();
}

You can also have your functions be stored in the array itself, but for just two functions, this indirect approach works fine. Let me know if you’d like to see what that might look like :slight_smile:

Cheers,
Kirupa

Oh wow! you’re amazing man!
Thank you so much for this.

I can add more function groups to it freely right?

edit:
while testing it did not work…
this is my current code:

const Discord = require("discord.js");

const client = new Discord.Client();

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

client.on('ready', async () => {

var server = client.guilds.get("716227489860681738");
var channel = server.channels.get("716227489860681743")

console.log(`Logged in as ${client.user.username}, ready to get this bread.`);
for (var i = 0; i < 1000000; i++) {
    function groupOne() {
    channel.send('1')
    await sleep(10000)
    channel.send('2');
    await sleep(10000)
  }
  
  function groupTwo() {
    channel.send('3')
    await sleep(10000)
    channel.send('4');
    await sleep(10000)
  }
  
  let groups = ["one", "two"];
  let group = groups[Math.floor(Math.random() * groups.length)];
  
  if (group == "one") {
    groupOne();
  } else {
    groupTwo();
  }
}


    });


client.login(process.env.token)

Do you see an error i am not?
its giving me 0 errors…

What are you trying to do with the for loop? Yes, you can add more function groups freely. I will share a revised version of the code to simplify that by removing the if statement :slight_smile: