Get one or Multiple Random Elements from an Array in JS

Last updated: Mar 3, 2024
8 min

#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
```Copied!```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.

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

#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
```Copied!```npm init -y

npm install lodash
``````

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

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

#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
```Copied!```function getRandomElement(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}

const arr = ['bobby', 'hadz', 'com'];

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.

index.js
```Copied!```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
```Copied!```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
```Copied!```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
```Copied!```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
```Copied!```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
```Copied!```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
```Copied!```function getRandomElement(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}

const arr = ['bobby', 'hadz', 'com'];

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
```Copied!```# ๐๏ธ initialize a package.json file
npm init -y

npm install lodash
``````

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

index.js
```Copied!```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.

#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
```Copied!```function getRandomElement(arr) {
return arr[~~(Math.random() * arr.length)];
}

const arr = ['bobby', 'hadz', 'com'];

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`.

index.js
```Copied!```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
```Copied!```const obj = {
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

``````

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
```Copied!```const obj = {
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
```Copied!```const obj = {
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
``````

The `Object.values()` method returns an array of the object's values.

index.js
```Copied!```const obj = {
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
```Copied!```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
```Copied!```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
```Copied!```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
```Copied!```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
```Copied!```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
```Copied!```const obj = {
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

``````

#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
```Copied!```# ๐๏ธ initialize a package.json file
npm init -y

npm install lodash
``````

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

index.js
```Copied!```import _ from 'lodash';

const obj = {
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.

index.js
```Copied!```import _ from 'lodash';

const obj = {
country: 'Chile',
age: 30,
};

const values = Object.values(obj);

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
```Copied!```import _ from 'lodash';

const obj = {
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.

index.js
```Copied!```import _ from 'lodash';

const obj = {
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' ]
``````