Sling Academy
Home/JavaScript/JavaScript: 2 Ways to Get a Random Element from an Array

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

Last updated: February 19, 2023

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.

Next Article: JavaScript: How to iterate through 2 arrays in parallel

Previous Article: JavaScript: Find the mode of an array (the most common element)

Series: Working with Arrays in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration