# Picking a Random Item from an Array

**URL:** <https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178>\
**Category:** programming\
**Created:** [December 2, 2014, 12:27am UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178 "2014-12-02T00:27:34Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [December 2, 2014, 12:27am UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/1 "2014-12-02T00:27:39Z")

</div>

by [kirupa](http://www.kirupa.com/me/index.htm) | 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](http://www.kirupa.com/html5/picking_random_item_from_array.htm)

---

<div class="post-metadata">

**Author:** ![Olivia2](https://avatars.discourse-cdn.com/v4/letter/o/eada6e/32.png) [@Olivia2](https://forum.kirupa.com/u/Olivia2)\
**Post date:** [July 19, 2015, 6:50pm UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/2 "2015-07-19T18:50:39Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [July 20, 2015, 6:52am UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/3 "2015-07-20T06:52:17Z")

</div>

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](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? 😄

Cheers,  
Kirupa

---

<div class="post-metadata">

**Author:** ![JDS](https://avatars.discourse-cdn.com/v4/letter/j/b19c9b/32.png) [@JDS](https://forum.kirupa.com/u/JDS)\
**Post date:** [August 28, 2017, 8:33pm UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/4 "2017-08-28T20:33:19Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [August 29, 2017, 6:19am UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/5 "2017-08-29T06:19:32Z")

</div>

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](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](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 🙂

---

<div class="post-metadata">

**Author:** ![JDS](https://avatars.discourse-cdn.com/v4/letter/j/b19c9b/32.png) [@JDS](https://forum.kirupa.com/u/JDS)\
**Post date:** [August 29, 2017, 2:07pm UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/6 "2017-08-29T14:07:52Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [August 30, 2017, 3:10pm UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/7 "2017-08-30T15:10:34Z")

</div>

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](https://www.kirupa.com/html5/modifying_dom_elements.htm) (The entire section on the DOM ([https://www.kirupa.com/javascript/learn\_javascript.htm](https://www.kirupa.com/javascript/learn_javascript.htm)) . may be helpful if this is your first foray into this part of web development 🙂

---

<div class="post-metadata">

**Author:** ![amritpal](https://avatars.discourse-cdn.com/v4/letter/a/e0b2c6/32.png) [@amritpal](https://forum.kirupa.com/u/amritpal)\
**Post date:** [November 5, 2020, 11:10pm UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/8 "2020-11-05T23:10:36Z")

</div>

how can we do this same code in c?

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

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [November 6, 2020, 7:14pm UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/9 "2020-11-06T19:14:36Z")

</div>

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

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

---

<div class="post-metadata">

**Author:** ![kunni](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kunni/32/13115_2.png) [@kunni](https://forum.kirupa.com/u/kunni)\
**Post date:** [December 15, 2020, 12:56pm UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/10 "2020-12-15T12:56:00Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [December 16, 2020, 6:57pm UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/11 "2020-12-16T18:57:47Z")

</div>

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:

> **[Shuffling an Array](https://www.kirupa.com/html5/shuffling_array_js.htm)**
>
> Use the Fisher-Yates / Knuth approach to quickly shuffle the contents of an array in JavaScript.

🙂

---

<div class="post-metadata">

**Author:** ![Swosh\_js](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/swosh_js/32/13456_2.png) [@Swosh\_js](https://forum.kirupa.com/u/Swosh_js)\
**Post date:** [January 29, 2021, 2:18am UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/12 "2021-01-29T02:18:52Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Swosh\_js](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/swosh_js/32/13456_2.png) [@Swosh\_js](https://forum.kirupa.com/u/Swosh_js)\
**Post date:** [January 29, 2021, 2:44am UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/13 "2021-01-29T02:44:07Z")

</div>

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)];

```auto
thanks in advance
```

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [January 29, 2021, 6:12am UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/14 "2021-01-29T06:12:31Z")

</div>

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.

😀

---

<div class="post-metadata">

**Author:** ![Danila](https://avatars.discourse-cdn.com/v4/letter/d/0ea827/32.png) [@Danila](https://forum.kirupa.com/u/Danila)\
**Post date:** [May 8, 2021, 12:33pm UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/15 "2021-05-08T12:33:51Z")

</div>

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.

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

```

which that would be “group 1” ^

```auto
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 🙂

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [May 9, 2021, 3:05pm UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/16 "2021-05-09T15:05:00Z")

</div>

I can look at it later tonight 🙂

Are you running in a Node environment?

---

<div class="post-metadata">

**Author:** ![Danila](https://avatars.discourse-cdn.com/v4/letter/d/0ea827/32.png) [@Danila](https://forum.kirupa.com/u/Danila)\
**Post date:** [May 9, 2021, 10:01pm UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/17 "2021-05-09T22:01:31Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [May 10, 2021, 3:51am UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/18 "2021-05-10T03:51:53Z")

</div>

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

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 🙂

Cheers,  
Kirupa

---

<div class="post-metadata">

**Author:** ![Danila](https://avatars.discourse-cdn.com/v4/letter/d/0ea827/32.png) [@Danila](https://forum.kirupa.com/u/Danila)\
**Post date:** [May 10, 2021, 4:32am UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/19 "2021-05-10T04:32:04Z")

</div>

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:

```auto
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…

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [May 10, 2021, 1:29pm UTC](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178/20 "2021-05-10T13:29:31Z")

</div>

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 🙂

[Next page](https://forum.kirupa.com/t/picking-a-random-item-from-an-array/399178.md?page=2)
