The idea is to calculate a random array index and use it to get the array element. Let us say you have the following JS array.
var myArr = ['January', 'February', 'March'];
Every array element has an index by default. You can easily get an element using its index as array_name[index]. We just need to obtain a random number and use it as an index to get the element.
For this purpose, we will use the following function. It returns a random number between 0(inclusive) and 1 (exclusive).
We will multiply this with the number of elements in our array, myArr.length.
Since the above result may not be an integer we call Math.floor() function on it which will round down the number to the nearest integer.
Math.floor(Math.random() * myArr.length)
For example, if Math.random() returns 0.4, then the index will be Math.floor(0.4*3)= Math.floor(1.2)=1. You can use this index to get your array element.
myArr[Math.floor(Math.random() * myArr.length)];//February
If you have third party libraries like Underscore or Lodash, then you can use the sample() function to get a random element from array.
_.sample(['January', 'February', 'March']);
How to Include HTML in Another HTML File