Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu June 03, 2023 › #Array #Element

How to get a random item from a JavaScript array

 Hello guys, if you want to get a random item from an array in JavaScript, then in this article, you will know that how you can easily select a random value from an array using JavaScript.

Example

You can access every item of an array using its index. For example,you want to get the first element of an array, use array[0],to get the second item use array[1], and so on.

  1. Math.random() method is used to get a random number between 0 to 1 (1 exclusive).
  2. To get the numbers between 0 to array length, multiply the Math.random() value by array length.
  3. The result will be a decimal number. So, round the result to the nearest integer that is equal to or lower than the random value using Math.floor() method.
save
listen
AI Answer
1 Answer
Write Your Answer
  1. It's easy to use array.sort() method to sort the array.
    <script>
    let list = [2,3,5];
    let item = list.sort(function() {return 0.5 - Math.random()});

    alert(item[0]) ;
    </script>


    item is an array so use item[0] to get the first item.
    Reply Delete
    Share
loading
back
View All