Get one or Multiple Random Elements from an Array in JS

avatar
Borislav Hadzhiev

Last updated: Mar 3, 2024
8 min

banner

# Table of Contents

  1. Get Multiple Random Elements from an Array in JavaScript
  2. Get One random Element from an Array in JavaScript
  3. Get a Random Property from an Object in JavaScript

# Get Multiple Random Elements from an Array in JavaScript

To get multiple random elements from an array:

  1. Use the sort() method to shuffle the array.
  2. Use the slice() method on the shuffled array to get multiple random elements.
index.js
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']

get multiple random elements from array

The code for this article is available on GitHub

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.

index.js
const arr = ['bobby', 'hadz', '.', 'com']; arr.sort(); console.log(arr); // ๐Ÿ‘‰๏ธ [ '.', 'bobby', 'com', 'hadz' ]
The spread syntax (...) helps us to avoid mutating the passed-in array.

The only argument we passed to the sort() method is a compare function.

index.js
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.

index.js
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:

  • If the return value of the compare function is greater than 0, then element b gets sorted before a.
  • If the return value is less than 0, then element a gets sorted before b.
  • If the return value is equal to 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.

index.js
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:

NameDescription
start indexThe index of the first element to include in the returned array
end indexThe 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.

The slice method returns a new array containing multiple elements from the shuffled array.

This is a two-step process:

  1. Sort the array in random order.
  2. Get a slice from the shuffled array containing multiple elements.

Here's the complete example.

index.js
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']

# Table of Contents

  1. Get One random Element from an Array in JavaScript
  2. Get a Random Property from an Object in JavaScript

# Get Multiple Random Elements from an Array using lodash

Alternatively, you can use the lodash library.

First, make sure you have lodash installed by running the following command from your terminal.

shell
npm init -y npm install lodash

Now you can import and use the lodash.sampleSize() method.

index.js
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', '.' ]

get multiple random elements from array using lodash

The code for this article is available on GitHub

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:

# Get a random Element from an Array in JavaScript

To get a random element from an array:

  1. Use the Math.floor() and Math.random() methods to get a random index in the array.
  2. Use bracket notation to access the array at the random index.
index.js
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

get random element from array

The code for this article is available on GitHub

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.

index.js
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.

index.js
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.

index.js
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.

index.js
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).

index.js
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.

index.js
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.

index.js
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:

# Get a random element from an array using lodash

Alternatively, you can use the lodash library.

First, install the lodash module if you haven't already.

shell
# ๐Ÿ‘‡๏ธ initialize a package.json file npm init -y npm install lodash

You can now import and use the lodash.sample() method.

index.js
import _ from 'lodash'; const arr = ['bobby', 'hadz', 'com']; console.log(_.sample(arr)); // ๐Ÿ‘‰๏ธ bobby console.log(_.sample(arr)); // ๐Ÿ‘‰๏ธ com console.log(_.sample(arr)); // ๐Ÿ‘‰๏ธ bobby

get random element from array using lodash

The code for this article is available on GitHub

The sample() method returns a random element from the supplied collection.

# Get a random element from an array using Bitwise NOT (~)

You can also use the bitwise NOT (~) operator to get a random element from an array.

index.js
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

get random element from array using bitwise not

The code for this article is available on GitHub

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.

index.js
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.

# Get a Random Property from an Object in JavaScript

To get a random property from an object:

  1. Use the Object.keys() method to get an array of the object's keys.
  2. Use the Math.floor() and Math.random() functions to get a random index of the array.
  3. Use the random index to access one of the object's properties.
index.js
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

get random property from object

The code for this article is available on GitHub

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.

index.js
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().

index.js
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.

index.js
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.

index.js
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.

index.js
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.

index.js
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.

index.js
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.

index.js
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.

index.js
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

# Get a Random Property from an Object using lodash

Alternatively, you can use the lodash library.

First, install the lodash module if you haven't already.

shell
# ๐Ÿ‘‡๏ธ initialize a package.json file npm init -y npm install lodash

You can now import and use the lodash.sample() method.

index.js
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

get random property from object using lodash

The code for this article is available on GitHub

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.

index.js
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

# Get multiple random properties from an object

If you need to get multiple random properties from an object, use the lodash.sampleSize method.

index.js
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' ]

get multiple random properties from object

The code for this article is available on GitHub

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.

index.js
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' ]

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev