JavaScript: 2 Ways to Get a Random Element from an Array

Updated: February 19, 2023 By: Khue Post a comment

This concise, code-centric article shows you 2 different ways to get a random element from a given array in Javascript. Without any further ado, let’s get started.

Creating a Random Index

The key points of this approach are:

  • Create a random integer in the range from 0 (inclusive) to the length of the array (exclusive)
  • Use this random integer as an index to retrieve an array element

Example:

const arr = ['dog', 'cat', 'dragon','slingacademy.com', 'banana'];

// Create a random index 
const randomIndex = Math.floor(Math.random() * arr.length);

// Get the random item
const randomItem = arr[randomIndex];

console.log(randomItem);

Output:

dragon

The result may change each time you run the code.

Shuffling Array

The main idea of this technique is:

  • Shuffle the positions of items in the array
  • Get the first item of the array

Here’s how we implement this idea in practice:

const arr = ['dog', 'cat', 'dragon','slingacademy.com', 'banana'];

// shuffle the array
const shuffled = arr.sort(() => 0.5 - Math.random());

// Get the first element from the shuffled array
const randomElement = shuffled[0];

console.log(randomElement);

Output:

slingacademy.com

Due to the randomness, your output might be different from mine.