How to Get a Random Value from an Array in JavaScript

08/02/2021

Contents

In this article, you will learn how to get a random value from an array in JavaScript.

Getting a random value from an array in JavaScript

In JavaScript, you can use several methods to get a random value from an array. Here are some methods you can use:

Using the Math.random() method

This method generates a random number between 0 and 1. You can multiply this number by the length of the array and use the Math.floor() method to round down to the nearest integer. This will give you a random index in the array, which you can use to access a random value.

Example

const arr = [1, 2, 3, 4, 5];
const randomIndex = Math.floor(Math.random() * arr.length);
const randomValue = arr[randomIndex];
console.log(randomValue); // Output: random value from the array

Using the Array.prototype.sort() method

This method sorts the array in place and allows you to specify a custom sorting function. You can use a function that generates a random number between -1 and 1 to shuffle the array randomly. Then, you can use the Array.prototype.shift() method to remove and return the first element of the shuffled array, which will be a random value.

Example

const arr = [1, 2, 3, 4, 5];
const shuffle = (array) => {
  array.sort(() => Math.random() - 0.5);
}
shuffle(arr);
const randomValue = arr.shift();
console.log(randomValue); // Output: random value from the array

Using the Array.prototype.reduce() method

This method allows you to iterate over the array and accumulate a value based on a callback function. You can use the Math.random() method to randomly decide whether to replace the accumulated value with the current value or not. This will give you a random value from the array.

Example

const arr = [1, 2, 3, 4, 5];
const randomValue = arr.reduce((acc, cur) => Math.random() < 0.5 ? cur : acc);
console.log(randomValue); // Output: random value from the array