Skip to content

How to Get One or More Random Elements from an Array in JavaScript

Learn the efficient JavaScript methods for selecting a single random element or multiple unique random items from an array using Math.random(), shuffling, or Lodash utilities.

Selecting a random element or a subset of random elements from an array is a common task in programming, useful for everything from games and simulations to A/B testing and data sampling. JavaScript's Math.random() is the core tool for this, but the implementation differs depending on whether you need one item or multiple.

This guide will teach you the standard, idiomatic methods for getting a single random element and for getting multiple unique random elements from an array.

The Core Tool: Math.random()

The Math.random() function is the foundation for all of these solutions. It returns a floating-point, pseudo-random number in the range from 0 (inclusive) to 1 (exclusive). We can scale this number to the length of our array to get a random index.

How to Get a Single Random Element

The most efficient way to get a single random element is to generate a random index within the bounds of the array.

The logic:

  1. Generate a random number between 0 and 1 using Math.random().
  2. Multiply this number by the array's length to get a value between 0 and array.length.
  3. Use Math.floor() to round this number down to the nearest whole number, giving you a valid index.
  4. Access the array at that random index.

Solution:

function getRandomElement(array) {
  // Check if the array is empty to avoid returning undefined
  if (array.length === 0) {
    return undefined;
  }
  
  const randomIndex = Math.floor(Math.random() * array.length);
  return array[randomIndex];
}

// Example Usage:
const fruits = ['apple', 'banana', 'cherry', 'date'];
console.log(getRandomElement(fruits)); // e.g., 'cherry'
console.log(getRandomElement(fruits)); // e.g., 'apple'

How to Get Multiple Random Elements

When you need to select multiple unique random elements, the best approach is to shuffle the array and then take the first N elements.

The logic:

  1. Create a shallow copy of the original array to avoid modifying it.
  2. Shuffle this new array into a random order. A common shuffling algorithm is the Fisher-Yates shuffle, but a simpler sort() with Math.random() is often sufficient for non-critical applications.
  3. Use the slice() method to take the first N elements from the shuffled array.

Solution:

function getMultipleRandom(array, num) {
  // Create a shallow copy and shuffle it
  const shuffled = [...array].sort(() => 0.5 - Math.random());
  
  // Get the first `num` elements
  return shuffled.slice(0, num);
}

// Example Usage:
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

console.log(getMultipleRandom(fruits, 3)); // e.g., ['date', 'apple', 'cherry']
console.log(getMultipleRandom(fruits, 2)); // e.g., ['banana', 'elderberry']

Why Shuffling is the Best Approach for Multiple Elements

The shuffling method guarantees that you will get unique elements.

A more naive approach of simply calling getRandomElement() in a loop could result in picking the same element more than once.

For example, let's see the problem with a Naive Loop in the following snippet of code:

const fruits = ['apple', 'banana', 'cherry'];

function getMultipleNaive(array, num) {
  const result = [];
  for (let i = 0; i < num; i++) {
    result.push(getRandomElement(array));
  }
  return result;
}

// This could return ['apple', 'apple'], which is not a unique sample.
console.log(getMultipleNaive(fruits, 2));

Using a Library (Lodash) for Simplicity

For projects that already include a utility library like Lodash, these operations become even simpler.

Example with Lodash library:

import _ from 'lodash';

const fruits = ['apple', 'banana', 'cherry', 'date'];

// Get a single random element
const randomFruit = _.sample(fruits);
console.log(randomFruit);

// Get multiple random elements
const randomFruits = _.sampleSize(fruits, 2);
console.log(randomFruits);

Conclusion

Selecting random elements from an array is a common task with clear, idiomatic solutions.

  • To get a single random element, the most efficient method is to generate a random index: arr[Math.floor(Math.random() * arr.length)].
  • To get multiple unique random elements, the recommended best practice is to shuffle a copy of the array and then slice the desired number of elements.
  • For projects that already use a utility library, methods like Lodash's .sample() and .sampleSize() provide the cleanest and most declarative syntax.
Navigation