Jump to content

Make randomizer w/ JS, etc.

Litbelb

I have some data that I need to make a randomizer for a website I am working on. It is text data, and I need to make a button that will show a randomly picked piece of data. I am not that good at JS, so if you could tell my the syntax of the code, that would be much, much appreciated.

Link to comment
Share on other sites

Link to post
Share on other sites

-> Moved to Programming

^^^^ That's my post ^^^^
<-- This is me --- That's your scrollbar -->
vvvv Who's there? vvvv

Link to comment
Share on other sites

Link to post
Share on other sites

On 10/9/2020 at 2:23 PM, Litbelb said:

I have some data that I need to make a randomizer for a website I am working on. It is text data, and I need to make a button that will show a randomly picked piece of data. I am not that good at JS, so if you could tell my the syntax of the code, that would be much, much appreciated.

If the items are in an array, its really simple to select one randomly. For example:

 

animals = ["Dog", "Cat", "Fish", "Bird"];

int random = Math.floor(Math.random() * animals.length);

console.log(animals[random]); // Select a random index and get the item at that index

 

Link to comment
Share on other sites

Link to post
Share on other sites

in our SDK at work, I made a function to shuffle an array based on Yates shuffle, but where you move the item to the front rather than the back.

 

export const shuffle = (list) => {
  const max = list.length;
  return list.reduce((acc, _current, index) => {
    const randomIndex = Math.floor(Math.random() * (max - index) + index);
    return [acc[randomIndex], ...acc.slice(0, randomIndex), ...acc.slice(randomIndex + 1)];
  }, [...list]);
};

I then you could use @johnroper100 example and pick a random index. Shuffling the list first means if you picked an index of 5 two times in a row it will most likely be different.

 

we just use a sample function to shuffle then pick n amount of items

 

export const sample = (list, count) => shuffle([...list]).slice(0, count);

 

 

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×