Sample an array using underscore.js

– 08/28/13

You have an array of names, and you want to write a function that accepts said array and returns a name at random. Note that this functionality may at some point be added to underscore.js core.

var names = ['Bob', 'Kelly', 'Sue'];

function sample(array){ 
  /* let's build this */ 
};

sample(names); 
// => 'Bob'

sample(names); 
// => 'Sue'

Method 1 - using _.random()

The first method relies on underscore’s random method, which takes two arguments, a min and a max. The idea here is to generate a random index, then return the value in the array at that index.

function sample(array){
  return array[ _.random(0, array.length-1) ]
}

Method 2 - using _.shuffle()

The second method relies on underscore’s shuffle method, which takes an array, and returns a copy of the array, shuffled using the Fisher-Yates shuffle algorithm.

function sample(array){
  return _.shuffle(array)[0]
}

Thoughts?

Do you have another method? Let me know on Twitter.