-3

Quick question, I have an array of objects:

var objects = [
  {username: jon, count: 5},
  {username: sally, count: 7},
  {username: mark, count: 9,
]

I want to output one of these objects at random so that I can access its properties and not just it's index. How do I do this?

mellows
  • 303
  • 1
  • 7
  • 27
  • Your answer already here http://stackoverflow.com/questions/5915096/get-random-item-from-javascript-array – 0xdw May 11 '16 at 15:40

2 Answers2

1

First calculate a random index:

var random_index = Math.floor(Math.random() * 3);
//                                            ^ Length of array

then access the object with that index:

var obj = objects[random_index];
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
0
var randomObject = objects[Math.floor(Math.random() * objects.length)];

Explanation: Math.random() gets you a value between 0 and 1, multiply that by objects.length to get a number between 0 and objects.length, and use Math.floor() to truncate the decimal portion. Return the value at that position of objects.

SuperFLEB
  • 204
  • 2
  • 11