_.sample

Gets a random element from array.

  1. // Underscore/Lodash
  2. const array = [0, 1, 2, 3, 4]
  3. const result = _.sample(array)
  4. console.log(result)
  5. // output: 2
  6.  
  7. // Native
  8. const array = [0, 1, 2, 3, 4]
  9. const sample = arr => {
  10. const len = arr == null ? 0 : arr.length
  11. return len ? arr[Math.floor(Math.random() * len)] : undefined
  12. }
  13.  
  14. const result = sample(array)
  15. console.log(result)
  16. // output: 2

Browser Support for Array.prototype.length() and Math.random()

ChromeEdgeFirefoxIEOperaSafari
1.0 ✔