Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a random item from a JavaScript array [duplicate]

var items = Array(523, 3452, 334, 31, ..., 5346);

How do I get random item from items?

like image 536
James Avatar asked May 06 '11 17:05

James


People also ask

How do you duplicate an array in JavaScript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.

What does math random () do?

The Math. random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.

How do you select a random item from a list in Java?

In order to get a random item from a List instance, you need to generate a random index number and then fetch an item by this generated index number using List. get() method. The key point here is to remember that you mustn't use an index that exceeds your List's size.


3 Answers

var item = items[Math.floor(Math.random()*items.length)];
like image 61
Kelly Avatar answered Oct 21 '22 19:10

Kelly


Use underscore (or loDash :)):

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];
like image 37
chim Avatar answered Oct 21 '22 20:10

chim


1. solution: define Array prototype

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

that will work on inline arrays

[2,3,5].random()

and of course predefined arrays

var list = [2,3,5]
list.random()

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])
like image 131
Dino Reic Avatar answered Oct 21 '22 21:10

Dino Reic