Javascript select random word from 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]];

answered Dec 29, 2010 at 0:06

Jacob RelkinJacob Relkin

158k32 gold badges341 silver badges318 bronze badges

5

If you've already got underscore or lodash included in your project you can use _.sample.

// will return one item randomly from the array
_.sample[['January', 'February', 'March']];

If you need to get more than one item randomly, you can pass that as a second argument in underscore:

// will return two items randomly from the array using underscore
_.sample[['January', 'February', 'March'], 2];

or use the _.sampleSize method in lodash:

// will return two items randomly from the array using lodash
_.sampleSize[['January', 'February', 'March'], 2];

answered Jun 19, 2015 at 18:40

Brendan NeeBrendan Nee

4,8652 gold badges32 silver badges32 bronze badges

1

You may consider defining a function on the Array prototype, in order to create a method [].sample[] which returns a random element.

First, to define the prototype function, place this snippet in your code:

Array.prototype.sample = function[]{
  return this[Math.floor[Math.random[]*this.length]];
}

Later, to sample a random element from the array, just call .sample[]:

[1,2,3,4].sample[] //=> a random element

I'm releasing these code snippets into the public domain, under the terms of the CC0 1.0 license.

answered Nov 24, 2015 at 23:52

Ben AubinBen Aubin

5,3462 gold badges33 silver badges54 bronze badges

5

~~ is much faster than Math.Floor[], so when it comes to performance optimization while producing output using UI elements, ~~ wins the game. MORE INFO

var rand = myArray[~~[Math.random[] * myArray.length]];

But if you know that the array is going to have millions of elements then you might want to reconsider between Bitwise Operator and Math.Floor[], as bitwise operators behave weirdly with large numbers. See below example explained with the output.

var number = Math.floor[14444323231.2]; // => 14444323231
var number = 14444323231.2 | 0; // => 1559421343

answered May 5, 2018 at 12:25

Ankur SoniAnkur Soni

5,3675 gold badges43 silver badges75 bronze badges

5

The shortest version:

var myArray = ['January', 'February', 'March']; 
var rand = myArray[[Math.random[] * myArray.length] | 0]
console.log[rand]

answered Jul 19, 2016 at 2:37

foxirisfoxiris

2,68230 silver badges30 bronze badges

4

Say you want to choose a random item that is different from the last time [not really random, but still a common requirement]...

/**
 * Return a random element from an array that is
 * different than `last` [as long as the array has > 1 items]. 
 * Return null if the array is empty.
*/
function getRandomDifferent[arr, last = undefined] {
  if [arr.length === 0] {
    return null;
  } else if [arr.length === 1] {
    return arr[0];
  } else {
    let num = 0;
    do {
      num = Math.floor[Math.random[] * arr.length];
    } while [arr[num] === last];
    return arr[num];
  }
}

Implement like this:

const arr = [1,2,3];
const r1 = getRandomDifferent[arr];
const r2 = getRandomDifferent[arr, r1]; // r2 is different than r1.

answered Aug 14, 2012 at 1:57

CrazyTimCrazyTim

6,1475 gold badges31 silver badges54 bronze badges

0

If you have fixed values [like a month name list] and want a one-line solution

var result = ['January', 'February', 'March'][Math.floor[Math.random[] * 3]]

The second part of the array is an access operation as described in Why does [5,6,8,7][1,2] = 8 in JavaScript?

answered Nov 28, 2014 at 14:58

I.G. PascualI.G. Pascual

5,6005 gold badges42 silver badges56 bronze badges

6

If you want to write it on one line, like Pascual's solution, another solution would be to write it using ES6's find function [based on the fact, that the probability of randomly selecting one out of n items is 1/n]:

var item = ['A', 'B', 'C', 'D'].find[[_, i, ar] => Math.random[] < 1 / [ar.length - i]];
console.log[item];

Use that approach for testing purposes and if there is a good reason to not save the array in a seperate variable only. Otherwise the other answers [floor[random[]*length and using a seperate function] are your way to go.

answered Sep 11, 2017 at 18:01

StephanStephan

1,87814 silver badges19 bronze badges

0

Faker.js has many utility functions for generating random test data. It is a good option in the context of a test suite:

const Faker = require['faker'];
Faker.random.arrayElement[['January', 'February', 'March']];

As commenters have mentioned, you generally should not use this library in production code.

answered Dec 12, 2017 at 20:42

NathanNathan

5,1902 gold badges24 silver badges27 bronze badges

5

If you need to fetch a random item more than once, then, obviously you would use a function. One way is to make that function a method of the Array.prototype, but that will normally get you shouted down for tampering with built in prototypes.

However, you can add the method to the specific array itself:

var months = ['January', 'February', 'March'];
months.random = function[] {
    return this[Math.floor[Math.random[]*this.length]];
};

That way you can use months.random[] as often as you like without interfering with the generic Array.prototype.

As with any random function, you run the risk of getting the same value successively. If you don’t want that, you will need to track the previous value with another property:

months.random=function[] {
    var random;
    while[[random=this[Math.floor[Math.random[]*this.length]]] == this.previous];
    this.previous=random;
    return random;
};

If you’re going to do this sort of thing often, and you don’t want to tamper with Array.prototype, you can do something like this:

function randomValue[] {
    return this[Math.floor[Math.random[]*this.length]];
}

var data = [ … ];
var moreData = [ … ];

data.random=randomValue;
moreData.random=randomValue;

answered Jul 12, 2021 at 3:54

ManngoManngo

11.9k8 gold badges70 silver badges91 bronze badges

Editing Array prototype can be harmful. Here it is a simple function to do the job.

function getArrayRandomElement [arr] {
  if [arr && arr.length] {
    return arr[Math.floor[Math.random[] * arr.length]];
  }
  // The undefined will be returned if the empty array was passed
}

Usage:

// Example 1
var item = getArrayRandomElement[['January', 'February', 'March']];

// Example 2
var myArray = ['January', 'February', 'March'];
var item = getArrayRandomElement[myArray];

answered Sep 5, 2018 at 22:48

SeagullSeagull

3,1561 gold badge28 silver badges37 bronze badges

To get crypto-strong random item form array use

let rndItem = a=> a[rnd[]*a.length|0];
let rnd = []=> crypto.getRandomValues[new Uint32Array[1]][0]/2**32;

var myArray = ['January', 'February', 'March'];

console.log[ rndItem[myArray] ]

answered Sep 16, 2019 at 10:17

Kamil KiełczewskiKamil Kiełczewski

75.4k26 gold badges335 silver badges311 bronze badges

Recursive, standalone function which can return any number of items [identical to lodash.sampleSize]:

function getRandomElementsFromArray[array, numberOfRandomElementsToExtract = 1] {
    const elements = [];

    function getRandomElement[arr] {
        if [elements.length < numberOfRandomElementsToExtract] {
            const index = Math.floor[Math.random[] * arr.length]
            const element = arr.splice[index, 1][0];

            elements.push[element]

            return getRandomElement[arr]
        } else {
            return elements
        }
    }

    return getRandomElement[[...array]]
}

answered Dec 8, 2017 at 14:23

dwiltdwilt

5678 silver badges13 bronze badges

This is similar to, but more general than, @Jacob Relkin's solution:

This is ES2015:

const randomChoice = arr => {
    const randIndex = Math.floor[Math.random[] * arr.length];
    return arr[randIndex];
};

The code works by selecting a random number between 0 and the length of the array, then returning the item at that index.

answered Jan 2, 2016 at 15:23

Max HeiberMax Heiber

12.9k11 gold badges55 silver badges86 bronze badges

var item = myArray[Math.floor[Math.random[]*myArray.length]];

or equivalent shorter version:

var item = myArray[[Math.random[]*myArray.length]|0];

Sample code:

var myArray = ['January', 'February', 'March'];    
var item = myArray[[Math.random[]*myArray.length]|0];
console.log['item:', item];

answered May 19, 2017 at 9:01

Pavel PPavel P

15.1k11 gold badges75 silver badges119 bronze badges

Simple Function :

var myArray = ['January', 'February', 'March'];
function random[array] {
     return array[Math.floor[Math.random[] * array.length]]
}
random[myArray];

OR

var myArray = ['January', 'February', 'March'];
function random[] {
     return myArray[Math.floor[Math.random[] * myArray.length]]
}
random[];

OR

var myArray = ['January', 'February', 'March'];
function random[] {
     return myArray[Math.floor[Math.random[] * myArray.length]]
}
random[];

answered Dec 17, 2017 at 5:42

1

In my opinion, better than messing around with prototypes , or declaring it just in time, I prefer exposing it to window:

window.choice = function[] {
  if [!this.length || this.length == 0] return;
  if [this.length == 1] return this[0];
  return this[Math.floor[Math.random[]*this.length]];
}

Now anywhere on your app you call it like:

var rand = window.choice.call[array]

This way you can still use for[x in array] loop properly

answered May 13, 2014 at 10:27

weiskweisk

2,3801 gold badge17 silver badges18 bronze badges

3

I've found a way around the top answer's complications, just by concatenating the variable rand to another variable that allows that number to be displayed inside the calling of myArray[];. By deleting the new array created and toying around with it's complications, I've come up with a working solution:





var myArray = ['January', 'February', 'March', 'April', 'May']; var rand = Math.floor[Math.random[] * myArray.length]; var concat = myArray[rand]; function random[] { document.getElementById["demo"].innerHTML = [concat]; } Working Random Array generator

answered Apr 27, 2016 at 22:01

2

static generateMonth[] { 
const theDate = ['January', 'February', 'March']; 
const randomNumber = Math.floor[Math.random[]*3];
return theDate[randomNumber];
};

You set a constant variable to the array, you then have another constant that chooses randomly between the three objects in the array and then the function simply returns the results.

answered Mar 15, 2018 at 7:51

Neil MeyerNeil Meyer

4213 silver badges10 bronze badges

Looking for a true one-liner I came to this:

['January', 'February', 'March'].reduce[[a, c, i, o] => { return o[Math.floor[Math.random[] * Math.floor[o.length]]]; }]

answered Jul 24, 2020 at 1:47

blagusblagus

1,7964 gold badges17 silver badges20 bronze badges

By adding a method on prototype of array you can get random values easly.

In this example you can get single or multiple random values from array.

You can run to test code by clicking snippet button.

Array.prototype.random = function[n]{
  if[n&&n>1]{
    const a = [];
    for[let i = 0;i len]
    count = len;

  for [let i = 0; i < count; i++] {
    let index;
    do {
      index = ~~[Math.random[] * len];
    } while [index in lookup];
    lookup[index] = null;
    tmp.push[arr[index]];
  }

  return tmp;
}

answered Oct 11, 2018 at 11:37

RafaelRafael

7,38913 gold badges32 silver badges45 bronze badges

Here is an example of how to do it:

$scope.ctx.skills = data.result.skills;
    $scope.praiseTextArray = [
    "Hooray",
    "You\'re ready to move to a new skill", 
    "Yahoo! You completed a problem", 
    "You\'re doing great",  
    "You succeeded", 
    "That was a brave effort trying new problems", 
    "Your brain was working hard",
    "All your hard work is paying off",
    "Very nice job!, Let\'s see what you can do next",
    "Well done",
    "That was excellent work",
    "Awesome job",
    "You must feel good about doing such a great job",
    "Right on",
    "Great thinking",
    "Wonderful work",
    "You were right on top of that one",
    "Beautiful job",
    "Way to go",
    "Sensational effort"
  ];

  $scope.praiseTextWord = $scope.praiseTextArray[Math.floor[Math.random[]*$scope.praiseTextArray.length]];

mech

2,6265 gold badges29 silver badges37 bronze badges

answered Feb 18, 2016 at 19:39

0

Create one random value and pass to array

Please try following code..

//For Search textbox random value
var myPlaceHolderArray = ['Hotels in New York...', 'Hotels in San Francisco...', 'Hotels Near Disney World...', 'Hotels in Atlanta...'];
var rand = Math.floor[Math.random[] * myPlaceHolderArray.length];
var Placeholdervalue = myPlaceHolderArray[rand];

alert[Placeholdervalue];

answered Feb 3, 2017 at 12:49

1

randojs makes this a little more simple and readable:

console.log[ rando[['January', 'February', 'March']].value ];

answered Dec 2, 2019 at 2:47

1

I am really surprised nobody tried to use native random values:

array[Date.now[]%array.length]

It will not work for array length over 160000000000, but I am sure you will never create arrays like this

UPD

As far as you question is how to pick random value from array called myArray [with len=3], the solution should be:

myArray[Date.now[]%myArray.length]

answered Nov 3, 2021 at 5:38

EgorEgor

2354 silver badges19 bronze badges

5

How do I select a random word in Javascript?

You can use Math. random[] to get a random number beteween 0 and 1. If you want a whole random number between 0 and 2. [so: 0, 1 or 2].

How do you get a random object from an array?

Example: Get Random Item From an Array.
A random number between 0 to array. length is generated using the Math. random[] method..
The Math. floor[] returns the nearest integer value generated by Math. random[] ..
This random index is then used to access a random array element..

How do you generate a random number in Javascript?

Javascript creates pseudo-random numbers with the function Math. random[] . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.

How do you select a random element from an array in Python?

Use the numpy. random. choice[] function to generate the random choices and samples from a NumPy multidimensional array. Using this function we can get single or multiple random numbers from the n-dimensional array with or without replacement.

Chủ Đề