how to get a random item from an array javascript

How to get a random item from an array in Javascript?

Getting a random item from an array in Javascript is a common problem that developers encounter. There are different methods to achieve this, but here are some of the most straightforward ones:

Method 1: Using Math.random() and Math.floor()

One way to get a random item from an array is by using the Math.random() method and the Math.floor() method to generate a random index within the array. Here's how to do it:


let arr = ['apple', 'banana', 'orange', 'kiwi'];
let randomItem = arr[Math.floor(Math.random() * arr.length)];
console.log(randomItem);
  • The "arr" variable holds the array of items you want to pick from.
  • The "Math.random()" method generates a random number between 0 and 1 (not including 1).
  • The "Math.floor()" method rounds down the random number generated by "Math.random()" to the nearest integer.
  • The "arr.length" property gets the length of the array.
  • The "randomItem" variable gets assigned the item at the index generated by "Math.floor(Math.random() * arr.length)".
  • Finally, we log the "randomItem" variable to the console to check if it worked.

Method 2: Using a for loop and Array.splice()

Another way to get a random item from an array is by using a for loop and the Array.splice() method to remove a random item from the array. Here's how to do it:


let arr = ['apple', 'banana', 'orange', 'kiwi'];
let randomItemIndex = Math.floor(Math.random() * arr.length);
let randomItem = arr[randomItemIndex];
arr.splice(randomItemIndex, 1);
console.log(randomItem);
console.log(arr);
  • The "arr" variable holds the array of items you want to pick from.
  • The "Math.random()" method generates a random number between 0 and 1 (not including 1).
  • The "Math.floor()" method rounds down the random number generated by "Math.random()" to the nearest integer.
  • The "arr.length" property gets the length of the array.
  • The "randomItemIndex" variable gets assigned the index of a random item in the array.
  • The "randomItem" variable gets assigned the item at the index generated by "randomItemIndex".
  • The "Array.splice()" method removes one element from the array starting at the index generated by "randomItemIndex".
  • Finally, we log the "randomItem" variable and the updated "arr" array to the console to check if it worked.

These are just two ways of getting a random item from an array in Javascript. There are many other methods and variations depending on your needs and preferences. The most important thing is to understand how arrays and random numbers work in Javascript and choose the method that works best for your particular case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe