How to get Random value from an array in javascript

This example covers below examples on Random Array Numbers in javascript Let’s declare an array

var array = [1, 2, 3, 4];

Here elements index starts from zero, and the end index is an array.length-1, i.e 1

Javascript random number from array example

There are multiple ways we can generate random numbers from an Array

  • use Math.random() function

Math.random() generates the random number between 0 and 1.

number is multiplied by the array length, the number always returns between 0 and to array length, This is called the random Index. Math.floor()returns an integer for a lower value of a floating

var array = [1, 2, 3, 4];
let randomIndex = Math.floor(Math.random() * array.length);
var randomNumber = array[randomIndex];
console.log(randomNumber); // returns 1 or 2 or 3 or 4
  • use Lodash or underscore sample function

The sample() function in lodash/underscore returns the random number for a given list of items.

syntax:

_.sample(list, [Optional Count])

List is an Array or set Optional Count- Number of Random numbers returned, Optional, Default is 1

Here is an example

var array = [1, 2, 3, 4];
console.log(_.sample(array)); // returns 1 or 2 or 3 or 4
console.log(_.sample(array, 3)); // returns array of three random numbers

Another function, sampleSize() in lodash also does the same thing.

var array = [1, 2, 3, 4];
console.log(_.sampleSize(array)); // returns 1 or 2 or 3 or 4
console.log(_.sampleSize(array, 3)); // returns array of three random numbers

Conclusion

To conclude, Learn how to get Random numbers from an array of numbers in JavaScript.