Generate random values from an array in JavaScript
This post will discuss how to generate random values from an array in JavaScript, which means selecting one or more values from the array at random, without any specific order or pattern.
1. Using the Math.random() and Math.floor() functions
The simplest and most straightforward way to generate random values from an array in JavaScript is to use the built-in functions random() and floor() of the Math object. The Math.random() function returns a random number between 0 (inclusive) and 1 (exclusive) and the Math.floor() function returns the largest integer that is less than or equal to a given number. By combining these two functions, we can generate a random index within the range of the array’s length. For example:
|
1 2 3 4 5 6 7 8 9 |
var arr = [ 1, 2, 3, 4, 5 ]; // Generate a random index between 0 and arr.length - 1 var index = Math.floor(Math.random() * arr.length); // Get the corresponding value var random = arr[index]; console.log(random); |
This method works with any kind of values in the array, such as numbers, strings, objects, or other arrays. This method can also be extended to generate multiple random values from an array by using a loop or a recursive function. However, it has some drawbacks. First, it can produce duplicate values, as the same index can be generated more than once. Second, it can be inefficient and slow, as it requires multiple calls to Math.random() and Math.floor(). Third, it can be inaccurate and biased, as Math.random() is not truly random but pseudo-random.
2. Using the Array.prototype.sort() function
Another way to generate random values from an array in JavaScript is to use the Array.prototype.sort() function, which sorts the elements of an array. To generate random values from an array using sort(), we need to provide a compare function that returns a random number between -0.5 and 0.5. This will shuffle or mix the elements of the array in a random order. For example:
|
1 2 3 4 5 6 7 8 9 |
var arr = [1, 2, 3, 4, 5]; // Sort the elements of the array using a random compare function arr.sort(function() { return Math.random() - 0.5; }); // Log the sorted array of randomly ordered values console.log(arr); |
This function can also be used to generate multiple random values from an array by using the Array.prototype.slice() function. This function returns a shallow copy of a portion of an array into a new array. We can use this function to get the first n elements of the shuffled array. For example:
|
1 2 3 4 5 6 7 8 9 10 11 |
var arr = [1, 2, 3, 4, 5]; // Sort the elements of the array using a random compare function arr.sort(function() { return Math.random() - 0.5; }); // Get the first 3 elements of the sorted array using slice() var result = arr.slice(0, 3); console.log(result); |
This function works with any kind of values in the array, such as numbers, strings, objects, or other arrays. However, this function also has some limitations and challenges that we should be aware of: It modifies the original array, which can cause side effects or errors if we need to preserve or access the original order of the elements. We need to create a copy of the original array if we want to avoid modifying it, which can consume extra memory and time. Also, we need to be careful when sorting objects or arrays, as they are compared by reference, not by value.
3. Using third-party libraries
Another way to generate random values from an array in JavaScript using lodash or underscore libraries. Lodash and Underscore libraries provides several utility methods to generate random numbers:
1. Using _.sample method
The _.sample() method returns a random element from the collection passed as an argument. It is available in both lodash or underscore. For example:
|
1 2 3 4 5 |
var _ = require('underscore'); // or lodash var arr = [ 1, 2, 3, 4, 5 ]; var random = _.sample(arr); console.log(random); |
2. Using _.sampleSize method (Lodash only)
To generate multiple random values from an array, we can use the sampleSize() function from Lodash. This function will take the number of elements to sample and return an array of random values. For example:
|
1 2 3 4 5 |
var _ = require('lodash'); var arr = [ 1, 2, 3, 4, 5 ]; var random = _.sampleSize(arr, 2); console.log(random); |
That’s all about generating random values from an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)