{

How to get Random value from an array in javascript


javascript Array random number examples

This example covers how to get a random number from an array of 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 do

  • use Math.random() function

Math.random() generates the random number between 0 and 1 and it is multiplied by the array length and 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

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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.