Javascript random from array

pick a random item from a javascript array

I am making a bot that can respond to my messages. If i send Hi! to the bot, it will answer With Well, hello there! . I was just wondering, what do I do to give the bot multiple choices of answers? Is there a way to pick a random item from a responses array using JavaScript?

Could you spend some time first to show the relevant code you have and what you have tried to make it work?

5 Answers 5

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

var answers = [ "Hey", "Howdy", "Hello There", "Wotcha", "Alright gov'nor" ] var randomAnswer = answers[Math.floor(Math.random() * answers.length)]; console.log(randomAnswer);

You can use the _.sample method in lodash:

var responses = ["Well, hello there!", "Hello", "Hola", "Yo!", "What’s up?", "Hey there."]; console.log(_.sample(responses));
  • Use Math.random() function to get the random number between(0-1, 1 exclusive).
  • Multiply it by the array length to get the numbers between(0-arrayLength).
  • Use Math.floor() to get the index ranging from(0 to arrayLength-1).

const answers = [ «Hey», «Howdy», «Hello There», «Wotcha», «Alright gov’nor» ]; const randomlyPickedString=answers[Math.floor(Math.random() * answers.length)]; console.log(randomlyPickedString);

  • The random(a, b) method is used to generates a number between(a to b, b exclusive).
  • Taking the floor value to range the numbers from (1 to arrayLength).
  • Subtract 1 to get the index ranging from(0 to arrayLength-1).

const answers = [ «Hey», «Howdy», «Hello There», «Wotcha», «Alright gov’nor» ] ;
const randomlyPickedString=answers[Math.floor(random(1, 5))-1]; console.log(randomlyPickedString);

For ease of understanding the code, I have written created an extra variable(randomlyPickedString). You can use the code without it too.

Читайте также:  Поле загрузки файлов, которое мы заслужили

There’s no JavaScript «command» that allows you to do this. But what you can do, is pick an integer at random from 0 to the length of the array, and get the array of responses at that index:

var response = responses[ parseInt( Math.random() * responses.length ) ];

A more concise way to do this is:

var response = responses[ Math.random() * responses.length |0 ];

where | 0 indicates the bitwise-or with 0, which in this case just turns a floating point number ( Math.random() returns values from 0 to 1) into its lowest integer

that works as well, but I’m taking the examples for what he might end up starting with and what he might see online. If someone is advanced enough to know about Math.floor, they’re probably advanced enough to know about tricks like |0

You would first need an array of possible responses. Something like this:

var responses = ["Well hello there!","Hello","Hola!"]; 

You can then use the Math.random function. This function returns a decimal < 1, so you will need to convert it to an integer.

var responses = ["Well hello there!","Hello","Hola!"]; var responseIndex = Math.floor((Math.random() * 10) + 1); 

Also, use the modulus ( % ) operator to keep your random number within the confines of your array indexes:

var responses = ["Well hello there!","Hello","Hola!"]; var totalResponses = responses.length; var responseIndex = Math.floor((Math.random() * 10) + 1) % totalResponses; 

Finally, lookup your random response in the array:

var responses = ["Well hello there!","Hello","Hola!"]; var totalResponses = responses.length; var responseIndex = Math.floor((Math.random() * 10) + 1) % totalResponses; var response = responses[responseIndex]; alert(response); 

Источник

Javascript random from array

The only argument we passed to the sort() method is a compare function.

Copied!
function getMultipleRandom(arr, num) const shuffled = [. arr].sort(() => 0.5 - Math.random()); return shuffled.slice(0, num); >

The function gets called with a pair of array elements ( a and b ) and defines the sort order of the array.

We used the Math.random() function to get a randomly sorted array.

The Math.random() function returns a random number from 0 up to 1 .

Copied!
console.log(Math.random()) // 👉️ 0.99453534. console.log(Math.random()) // 👉️ 0384848858. console.log(Math.random()) // 👉️ 0.58584833. console.log(0.5 - Math.random()); // 👉️ -0.10394939. console.log(0.5 - Math.random()); // 👉️ 0.364345434. console.log(0.5 - Math.random()); // 👉️ 0.075445654.

The compare function we passed to the sort() method gets called with 2 array elements every time — a and b .

These are the 3 scenarios that could happen on each iteration:

  • If the return value of the compare function is greater than 0 , then element b gets sorted before a .
  • If the return value is less than 0 , then element a gets sorted before b .
  • If the return value is equal to 0 , then the original order of the array elements is kept.

The Math.random() function returns a float from 0 to 1 , so we picked a number in the middle ( 0.5 ) from which we subtract the result of calling Math.random() .

This basically shuffles the array.

The last step is to use the Array.slice method to get multiple elements from the shuffled array.

Copied!
function getMultipleRandom(arr, num) const shuffled = [. arr].sort(() => 0.5 - Math.random()); return shuffled.slice(0, num); >

The slice method takes the following 2 arguments:

Name Description
start index The index of the first element to include in the returned array
end index The index of the first element to exclude from the returned array

When only a single argument is passed to the Array.slice() method, the slice goes to the end of the array.

Источник

Как выбрать случайный элемент из массива js

Чтобы выбрать случайный элемент из массива можно воспользоваться методами Math.random() и Math.floor() :

Выбрать случайный элемент массива можно не только с помощью стандартных возможностей языка.
Давайте обратимся к библиотеке Lodash, там есть именно то, что нам нужно.

const movies = [ 'Star Wars', 'Pirates of the Caribbean', 'Lord of the Rings', 'Avengers', 'The Dark Fields', ]; //выбираем фильм на вечер с помощью метода _.sample() const random = _.sample(movies); console.log("Random:", random); // => Random: Pirates of the caribbean 

Познакомились с методом _.sample() и выбрали фильм на вечер.

Источник

Get a random item from a JavaScript array [duplicate]

This question is absolutely identical to Getting random value from an array, yet the Mighty Mods haven’t bothered to close it in 3+ years. Instead, they close «unconstructive» questions with hundreds of votes.

13 Answers 13

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

Math.random() will never be 1, nor should it. The largest index should always be one less than the length, or else you’ll get an undefined error.

@virus Math.round is not a valid substitution for Math.floor . Using round would cause accidentally referencing an undefined index, say in the case Math.random() is 0.95 and items.length is 5. Math.round(0.95*5) is 5, which would be an invalid index. floor(random) will always be zero in your example.

@aloisdg that’s true, as long as the array length is less than 2^31, which is still a very large number 🙂

1. solution: define Array prototype

Array.prototype.random = function ()

that will work on inline arrays

and of course predefined arrays

2. solution: define custom function that accepts list and returns element

function get_random (list) < return list[Math.floor((Math.random()*list.length))]; >get_random([2,3,5]) 

@EvanCarroll better reference a useful link instead of downvoting for subjective notions such as coding style which does not make the answer invalid nor «unuseful» ! stackoverflow.com/questions/14034180/…

Upvoted because downvoting for adding something to Array.prototype is not useful to anyone without explanation.

The issue with adding a new function to Array.prototype is the same issue as adding a global variable — someone/something else may be using the same «name» for something different — which can cause subtle mahem

Thank you for this. Far more usable than typing the whole vanilla formula or calling a custom function when the code requires it more than once. As for the valid concerns about conflicts, that’s what namespacing is for: ns. or ns_ format where applicable.

@Schmoo I just ran into one of those «subtle mayhem» situations. I shortened the prototype’s name to «rand». Then suddenly during a for (let i in arr) loop, it iterates all the expected indexes, and also iterates an index of «rand». Had to switch to a for (let i=0,l=arr.length;i

var randomArray = [ '#cc0000','#00cc00', '#0000cc' ]; // use _.sample var randomElement = _.sample(randomArray); // manually use _.random var randomElement = randomArray[_.random(randomArray.length-1)]; 

Or to shuffle an entire array:

// use underscore's shuffle function var firstRandomElement = _.shuffle(randomArray)[0]; 

Using underscore or lodash for just one function would be overkill, but if you’re doing any complicated js functionality then it can save hours or even days.

lodash is modularized on npm, so you can install just the sample function if you want: npmjs.com/package/lodash.sample

My creed is to use as few libraries as possible for any project. With that being said, I always end up using lodash. It’s too convenient to not use

If you really must use jQuery to solve this problem (NB: you shouldn’t):

(function($) < $.rand = function(arg) < if ($.isArray(arg)) < return arg[$.rand(arg.length)]; >else if (typeof arg === "number") < return Math.floor(Math.random() * arg); >else < return 4; // chosen by fair dice roll >>; >)(jQuery); var items = [523, 3452, 334, 31, . 5346]; var item = jQuery.rand(items); 

This plugin will return a random element if given an array, or a value from [0 .. n) given a number, or given anything else, a guaranteed random value!

For extra fun, the array return is generated by calling the function recursively based on the array’s length 🙂

Источник

How to get random elements from an array [duplicate]

I have a JavaScript Array and now want to randomly choose four different numbers from it and then express it on the page (through document.write ). Obviously each time the page is reloaded by the user it would show four different random numbers.

Actually this is not the same question as the supposed duplicate: getting more than one, different, properly random value from an array is significantly more complicated than just getting one random value.

@TimDown: Agreed. If this would be the same question as the supposed duplicate the answer(s) would be the same (same questions have same answers right?) which clearly are not.

4 Answers 4

You could shuffle the array and pick the first four.

Now numbers[0] , numbers[1] . and so on have random and unique elements.

Note that this method may not be an optimal way to shuffle an array: see Is it correct to use JavaScript Array.sort() method for shuffling? for discussion.

It hardly matters in this circumstance, but I find it interesting all the same; this method turns out not-to-be-so-random after all: sitepoint.com/…

Or number.filter(() => Math.round(Math.random()) to get random items and continue with sort in case it’s needed.

If you want this to be as random as the native implementations of JavaScript’s Math.random() will allow, you could use something like the following, which also has the advantages of leaving the original array untouched and only randomizing as much of the array as required:

function getRandomArrayElements(arr, count) < var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index; while (i-- >min) < index = Math.floor((i + 1) * Math.random()); temp = shuffled[index]; shuffled[index] = shuffled[i]; shuffled[i] = temp; >return shuffled.slice(min); > var numbers = ['1','2','4','5','6','7','8','9','10']; alert( getRandomArrayElements(numbers, 4) ); 
//return a random integer between 0 and 10 document.write(Math.floor(Math.random()*11)); 

Or document.write( numbers[ (Math.floor(Math.random()*11) ] ] ); which becomes increasingly important if the numbers array doesn’t contain something as trivial as 1-10.

@Nim Could be both ways, but I interpreted that part so that each page load should pull different (but unique) random numbers, not the sames that were shown the last time.

Источник

Оцените статью