Today I Learned

hashrocket A Hashrocket project

Sample from an array in JavaScript

There's no equivalent to Ruby's array.sample, so here's this:

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

I recently needed to pop a random item out of an array, changing the array in the process. That's just the above plus a splice:

Array.prototype.randomSample = function() {
  return this.splice(Math.floor(Math.random() * this.length), 1);
}

(You don't have to put them on the Array prototype, I'm just being cute here)

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.