Get a Random Item from a JavaScript Array

Get a random item from a JavaScript array

var item = items[Math.floor(Math.random()*items.length)];

Getting a random value from a JavaScript array

It's a simple one-liner:

const randomElement = array[Math.floor(Math.random() * array.length)];

For example:

const months = ["January", "February", "March", "April", "May", "June", "July"];

const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);

How to get a number of random elements from an array?

Try this non-destructive (and fast) function:

function getRandom(arr, n) {
var result = new Array(n),
len = arr.length,
taken = new Array(len);
if (n > len)
throw new RangeError("getRandom: more elements taken than available");
while (n--) {
var x = Math.floor(Math.random() * len);
result[n] = arr[x in taken ? taken[x] : x];
taken[x] = --len in taken ? taken[len] : len;
}
return result;
}

pick a random item from a javascript array

Use Math.random * the length of the array, rounded down, as an index into the array.

Like this:

var answers = [

"Hey",

"Howdy",

"Hello There",

"Wotcha",

"Alright gov'nor"

]

var randomAnswer = answers[Math.floor(Math.random() * answers.length)];

console.log(randomAnswer);

One random item per day from JavaScript array

Instead of using Math.random which will be differ in each run in each client, Generate random index based on day, month, and year. (This should same valid index when you run on same day)

const srcArray = [
"source1",
"source2",
"source3"
];

const source = document.querySelector("#video");

window.onload = () => generateRandomSrc(srcArray);

const random = () => {
const date = new Date();
return (date.getFullYear() * date.getDate() * (date.getMonth() + 1)) % srcArray.length;
}

function generateRandomSrc(array) {
source.innerText = `Today's video ${srcArray[random()]}`
}
<div id="video"> </div> 

How to get one random item from an array?

You can use "Math.random" function, like sharing you a sample.

const random = ["gm" , "hello" , "dance"," jump","clomb"]
const randomName = (name) => {
const random = Math.floor(Math.random() * name.length)
return name[random]
}

console.log(randomName(random))

Also adding code snippet :

const random = ["gm" , "hello" , "dance"," jump","clomb"]
const randomName = (name) => {
const random = Math.floor(Math.random() * name.length)
return name[random]
}

console.log(randomName(random))

How to Randomly Choose an Element from an Array that Wasn't Chosen before in JavaScript?

You can try something like this:

Idea

  • Create a utility function that takes an array and returns you a random value.
  • Inside this Array, maintain 2 array, choices and data.
  • In every iteration, remove 1 item from data and put it in chosenItems
  • Once the length of data reaches 0, set chosenItems or originalArray as data and repeat process.

Benefit of this approach would be,

  • You dont need to maintain and pass array variable.
  • It can be made generic and used multiple times.

function randomize(arr) {
let data = [...arr];
let chosenItems = [];

function getRandomValue() {
if (data.length === 0) {
data = chosenItems;
chosenItems = [];
}
const index = Math.floor(Math.random() * data.length);
const choice = data.splice(index, 1)[0];

chosenItems.push(choice);
return choice;
}

return {
randomItem: getRandomValue
}
}

const dummyData = [ 1,2,3,4,5 ];

const randomizeData = randomize(dummyData);

for (let i = 0; i< 10; i++) {
console.log(randomizeData.randomItem())
}

Picking a random item from array with equal distribution

If you can precompute the result (i.e. you need a finite number of results, not an infinite stream) and the number of results is divisible by the number of items, you can get a perfect distribution:

  1. Generate an array that repeats the items until you've got enough, i.e. [1, 2, 3, 1, 2, 3, 1, 2, 3, ...]. The array is thus guaranteed to have exactly as many instances of each item.
  2. Shuffle the array with a fair shuffle algorithm, e.g. Fisher-Yates. The array still has exactly as many instances of each item.

If you do need an infinite stream, you could use something like an "item bag" model (which, btw, is how the blocks in Tetris are chosen):

  1. Fill a "bag" with your items ([1, 2, 3]). Shuffle it (as above).
  2. When you need an item, pop the first one from the shuffled bag.
  3. If the bag is empty, re-fill it according to step 1.

The only case where this doesn't have a perfect distribution is if you stop "mid-bag".

Select a random object in javascript/jquery

A quick solution using plain javascript would be generate a random number and use it using Object.keys().

var keys = Object.keys(choose_one);
var randomKey = key[Math.floor(Math.random()*keys.length)];
var value = choose_one[randomKey];


Related Topics



Leave a reply



Submit