how to generate a random response from an array code example

Example 1: pick random string from array javascript

var groceries = [
'milk',
'coriander',
'cucumber',
'eggplant'
]
let mygroceries = groceries[Math.floor(Math.random() * groceries.length)]
console.log(mygroceries)//This gives you any string from groceries

Example 2: function that takes any question and returns a randomly selected item from an array

function randomNoRepeats(array) {
  var copy = array.slice(0);
  return function() {
    if (copy.length < 1) { copy = array.slice(0); }
    var index = Math.floor(Math.random() * copy.length);
    var item = copy[index];
    copy.splice(index, 1);
    return item;
  };
}

var chooser = randomNoRepeats(['Foo', 'Bar', 'Gah']);
chooser(); // => "Bar"
chooser(); // => "Foo"
chooser(); // => "Gah"
chooser(); // => "Foo" -- only repeats once all items are exhausted.

Tags:

Misc Example