Last updated: Mar 3, 2024
Reading timeยท8 min
To get multiple random elements from an array:
sort()
method to shuffle the array.slice()
method on the shuffled array to get multiple random
elements.function getMultipleRandom(arr, num) { const shuffled = [...arr].sort(() => 0.5 - Math.random()); return shuffled.slice(0, num); } const arr = ['b', 'c', 'a', 'd']; console.log(getMultipleRandom(arr, 2)); // ๐๏ธ ['a', 'c']; console.log(getMultipleRandom(arr, 3)); // ๐๏ธ ['c', 'b', 'c']
If you only need to get 1 random element from an array, click on the following subheading:
We created a reusable function that takes an array and the number of random elements we want to get back.
The first step is to use the spread syntax (...) to create a shallow copy of the original array.
This is necessary because the Array.sort() method mutates the original array.
const arr = ['bobby', 'hadz', '.', 'com']; arr.sort(); console.log(arr); // ๐๏ธ [ '.', 'bobby', 'com', 'hadz' ]
The only argument we passed to the sort()
method is a compare function.
function getMultipleRandom(arr, num) { const shuffled = [...arr].sort(() => 0.5 - Math.random()); return shuffled.slice(0, num); }
The function gets called with a pair of array elements (a
and b
) and defines
the sort order of the array.
We used the Math.random() function to get a randomly sorted array.
The Math.random()
function returns a random number from 0
up to 1
.
console.log(Math.random()) // ๐๏ธ 0.99453534... console.log(Math.random()) // ๐๏ธ 0384848858... console.log(Math.random()) // ๐๏ธ 0.58584833... console.log(0.5 - Math.random()); // ๐๏ธ -0.10394939... console.log(0.5 - Math.random()); // ๐๏ธ 0.364345434... console.log(0.5 - Math.random()); // ๐๏ธ 0.075445654...
The compare function we passed to the sort()
method gets called with 2 array
elements every time - a
and b
.
These are the 3 scenarios that could happen on each iteration:
0
, then element
b
gets sorted before a
.0
, then element a
gets sorted before b
.0
, then the original order of the array
elements is kept.The Math.random()
function returns a float from 0
to 1
, so we picked a
number in the middle (0.5
) from which we subtract the result of calling
Math.random()
.
This basically shuffles the array.
The last step is to use the Array.slice() method to get multiple elements from the shuffled array.
function getMultipleRandom(arr, num) { const shuffled = [...arr].sort(() => 0.5 - Math.random()); return shuffled.slice(0, num); }
The slice
method takes the following 2 arguments:
Name | Description |
---|---|
start index | The index of the first element to include in the returned array |
end index | The index of the first element to exclude from the returned array |
When only a single argument is passed to the Array.slice()
method, the slice
goes to the end of the array.
slice
method returns a new array containing multiple elements from the shuffled array.This is a two-step process:
Here's the complete example.
function getMultipleRandom(arr, num) { const shuffled = [...arr].sort(() => 0.5 - Math.random()); return shuffled.slice(0, num); } const arr = ['b', 'c', 'a', 'd']; console.log(getMultipleRandom(arr, 2)); // ๐๏ธ ['d', 'a']; console.log(getMultipleRandom(arr, 3)); // ๐๏ธ ['b', 'a', 'c']
lodash
Alternatively, you can use the lodash
library.
First, make sure you have lodash
installed by running the following command
from your terminal.
npm init -y npm install lodash
Now you can import and use the lodash.sampleSize() method.
import _ from 'lodash'; const arr = ['bobby', 'hadz', '.', 'com']; console.log(_.sampleSize(arr, 2)); // ๐๏ธ [ 'bobby', 'com' ] console.log(_.sampleSize(arr, 2)); // ๐๏ธ [ 'com', '.' ] console.log(_.sampleSize(arr, 3)); // ๐๏ธ [ 'hadz', 'bobby', '.' ] console.log(_.sampleSize(arr, 3)); // ๐๏ธ [ 'com', 'bobby', '.' ]
The sampleSize
method takes an array and n
as parameters and returns n
random elements from the array.
Note: If you need to get a random property from an object, click on the following subheading:
To get a random element from an array:
Math.floor()
and Math.random()
methods to get a random index in
the array.function getRandomElement(arr) { return arr[Math.floor(Math.random() * arr.length)]; } const arr = ['bobby', 'hadz', 'com']; console.log(getRandomElement(arr)); // ๐๏ธ hadz console.log(getRandomElement(arr)); // ๐๏ธ com console.log(getRandomElement(arr)); // ๐๏ธ bobby
The expression in the square brackets []
evaluates to a random index in the
array.
The Math.floor() function rounds a number down if the number has a decimal.
Otherwise, the function returns the number as is.
console.log(Math.floor(4.99)); // ๐๏ธ 4 console.log(Math.floor(4.01)); // ๐๏ธ 4 console.log(Math.floor(4)); // ๐๏ธ 4
The Math.random() function returns
a random number in the range 0
to less than 1
. The function could return
0
, but it could never return 1
.
console.log(Math.random()); // ๐๏ธ 0.5434554... console.log(Math.random()); // ๐๏ธ 0.3348588... console.log(Math.random()); // ๐๏ธ 0.8547547...
We multiplied the result of calling Math.round()
by the array's length.
function getRandomElement(arr) { return arr[Math.floor(Math.random() * arr.length)]; }
The max
value we could get is, if Math.random()
returns 0.9999...
and we
multiply the number by the array's length (3).
We would get a value of 2.997
.
console.log(0.999 * 3); // ๐๏ธ 2.997
However, JavaScript indexes are zero-based, so the last element in an array has
an index of array.length - 1
(3 - 1 = 2).
This is why we used the Math.floor()
function to round the number down to the
nearest integer, which is 2
(the last index in the array).
console.log(0.999 * 3); // ๐๏ธ 2.997 console.log(Math.floor(0.999 * 3)); // ๐๏ธ 2
Conversely, the min
value we could get is if Math.random()
returns 0
.
We would then multiply 0
by the array's length and get 0
back.
console.log(0 * 3); // ๐๏ธ 0
Calling the Math.floor()
function with 0
would return 0
and we would
access the first element in the array.
The expression returns an index from 0
up to (but not including)
array.length
.
When using this approach, we could never access an index out of bounds.
function getRandomElement(arr) { return arr[Math.floor(Math.random() * arr.length)]; } const arr = ['bobby', 'hadz', 'com']; console.log(getRandomElement(arr)); // ๐๏ธ hadz console.log(getRandomElement(arr)); // ๐๏ธ com console.log(getRandomElement(arr)); // ๐๏ธ bobby
The getRandomElement
function takes an array as a parameter and returns a
random element from the array.
Note: If you need to get a random property from an object, click on the following subheading:
lodash
Alternatively, you can use the lodash
library.
First, install the lodash
module if you haven't already.
# ๐๏ธ initialize a package.json file npm init -y npm install lodash
You can now import and use the lodash.sample() method.
import _ from 'lodash'; const arr = ['bobby', 'hadz', 'com']; console.log(_.sample(arr)); // ๐๏ธ bobby console.log(_.sample(arr)); // ๐๏ธ com console.log(_.sample(arr)); // ๐๏ธ bobby
The sample()
method returns a random element from the supplied collection.
You can also use the bitwise NOT (~) operator to get a random element from an array.
function getRandomElement(arr) { return arr[~~(Math.random() * arr.length)]; } const arr = ['bobby', 'hadz', 'com']; console.log(getRandomElement(arr)); // ๐๏ธ hadz console.log(getRandomElement(arr)); // ๐๏ธ com console.log(getRandomElement(arr)); // ๐๏ธ bobby
Notice that we replaced the call to the Math.floor()
method with two bitwise
NOT (~) operators.
The two
bitwise NOT (~)
operators round the number toward 0
.
console.log(~~1.9999); // ๐๏ธ 1 console.log(~~1.0011); // ๐๏ธ 1
This way we can be sure that the expression won't return an array index out of bounds.
Which approach you pick is a matter of personal preference. I'd use the
Math.floor()
option as I find it more explicit and quite intuitive.
To get a random property from an object:
Object.keys()
method to get an array of the object's keys.Math.floor()
and Math.random()
functions to get a random index of
the array.const obj = { name: 'bobby hadz', country: 'Chile', age: 30, }; function getRandomProperty(obj) { const keys = Object.keys(obj); return keys[Math.floor(Math.random() * keys.length)]; } console.log(getRandomProperty(obj)); // ๐๏ธ name console.log(getRandomProperty(obj)); // ๐๏ธ age console.log(getRandomProperty(obj)); // ๐๏ธ name console.log(obj[getRandomProperty(obj)]); // ๐๏ธ bobby hadz
We created a reusable function that returns a random property from an object.
The first step is to get an array of the object's keys using the Object.keys() method.
const obj = { name: 'bobby hadz', country: 'Chile', age: 30, }; // ๐๏ธ ['name', 'country', 'age'] console.log(Object.keys(obj));
If you need to get a random value from the object, you would use the
Object.values()
method instead of Object.keys()
.
const obj = { name: 'bobby hadz', country: 'Chile', age: 30, }; function getRandomValue(obj) { const values = Object.values(obj); return values[Math.floor(Math.random() * values.length)]; } console.log(getRandomValue(obj)); // ๐๏ธ Chile console.log(getRandomValue(obj)); // ๐๏ธ Chile console.log(getRandomValue(obj)); // ๐๏ธ bobby hadz
The Object.values()
method returns an array of the object's values.
const obj = { name: 'bobby hadz', country: 'Chile', age: 30, }; // ๐๏ธ [ 'bobby hadz', 'Chile', 30 ] console.log(Object.values(obj));
The Math.floor() function rounds a number down if the number has a decimal, otherwise, the function returns the number as is.
console.log(Math.floor(2.99)); // ๐๏ธ 2 console.log(Math.floor(2.01)); // ๐๏ธ 2 console.log(Math.floor(2)); // ๐๏ธ 2
The Math.random() function returns
a random number in the range 0
to less than 1
.
The function could return 0
, but it could never return 1
.
console.log(Math.random()); // ๐๏ธ 0.1034543... console.log(Math.random()); // ๐๏ธ 0.5438454... console.log(Math.random()); // ๐๏ธ 0.5438483... // ๐๏ธ Multiplied by keys.length const keys = ['name', 'country', 'age']; console.log(Math.random() * keys.length); // ๐๏ธ 2.534... console.log(Math.random() * keys.length); // ๐๏ธ 1.543... console.log(Math.random() * keys.length); // ๐๏ธ 1.754... console.log(Math.random() * keys.length); // ๐๏ธ 0.324...
The max
value we could get is if Math.random()
returns 0.999...
and we
multiply the number by the array's length (3).
We would get a value of 2.997
.
console.log(0.999 * 3); // ๐๏ธ 2.997
However, JavaScript indexes are zero-based, so the last element in an array has
an index of array.length - 1
.
This is why we used the Math.floor()
method to round the number down to the
next integer - 2
, which is the last index in the array of keys.
console.log(0.999 * 3); // ๐๏ธ 2.997 console.log(Math.floor(0.999 * 3)); // ๐๏ธ 2
Conversely, the min
value we could get is if Math.random()
returns 0
.
In this case, we would multiply 0
by the array's length and get 0
.
console.log(0 * 3); // ๐๏ธ 0
Calling the Math.floor()
method with 0
returns 0
.
In this scenario, we would access the first element in the keys array.
The expression returns an index from 0
, up to (but not including)
array.length
.
This guarantees us that we can never access an index that is out of bounds.
const obj = { name: 'bobby hadz', country: 'Chile', age: 30, }; function getRandomProperty(obj) { const keys = Object.keys(obj); return keys[Math.floor(Math.random() * keys.length)]; } console.log(getRandomProperty(obj)); // ๐๏ธ name console.log(getRandomProperty(obj)); // ๐๏ธ age console.log(getRandomProperty(obj)); // ๐๏ธ name console.log(obj[getRandomProperty(obj)]); // ๐๏ธ bobby hadz
lodash
Alternatively, you can use the lodash
library.
First, install the lodash
module if you haven't already.
# ๐๏ธ initialize a package.json file npm init -y npm install lodash
You can now import and use the lodash.sample() method.
import _ from 'lodash'; const obj = { name: 'bobby hadz', country: 'Chile', age: 30, }; const keys = Object.keys(obj); console.log(_.sample(keys)); // ๐๏ธ name console.log(_.sample(keys)); // ๐๏ธ name console.log(_.sample(keys)); // ๐๏ธ country
We used the Object.keys()
method to get an array of the object's keys and used
the lodash.sample()
method to pick a random element from the collection.
If you need to get a random value from the object, use the Object.values()
method to get an array of the object's values.
import _ from 'lodash'; const obj = { name: 'bobby hadz', country: 'Chile', age: 30, }; const values = Object.values(obj); console.log(_.sample(values)); // ๐๏ธ bobby hadz console.log(_.sample(values)); // ๐๏ธ Chile console.log(_.sample(values)); // ๐๏ธ 30
If you need to get multiple random properties from an object, use the
lodash.sampleSize
method.
import _ from 'lodash'; const obj = { name: 'bobby hadz', country: 'Chile', age: 30, }; const keys = Object.keys(obj); console.log(_.sampleSize(keys, 2)); // ๐๏ธ [ 'name', 'country' ] console.log(_.sampleSize(keys, 2)); // ๐๏ธ [ 'age', 'country' ] console.log(_.sampleSize(keys, 2)); // ๐๏ธ [ 'age', 'country' ]
The sampleSize method takes a
collection and n
as parameters and returns n
random elements from the
collection.
You can use the same approach to get multiple random values from an object.
import _ from 'lodash'; const obj = { name: 'bobby hadz', country: 'Chile', age: 30, }; const values = Object.values(obj); console.log(_.sampleSize(values, 2)); // ๐๏ธ [ 30, 'Chile' ] console.log(_.sampleSize(values, 2)); // ๐๏ธ [ 'Chile', 30 ] console.log(_.sampleSize(values, 2)); // ๐๏ธ [ 30, 'bobby hadz' ]
You can learn more about the related topics by checking out the following tutorials: