Search code examples
javascriptarraysrandomsentence

Combine random array items into sentence


What I'm trying to do is basically take the below code and make it work so that I can combine items from several arrays into one sentence. So for instance, right now if I run this code it will give me random items from myarray, i.e. item1, 2, etc. But what I would like to do is create several arrays and have the result be a sentence which includes (in this order) random items from array1, array2, array3, etc. Basically, a random sentence generator using arrays. What differs between this and proposed duplicate item is that I already know how to randomize items within a single array, but would like to combine several array items into one sentence structure. (array1 item) + (array2 item) + (array3 item)

 function GetValue()
{
var myarray= new Array("item1","item2","item3");
var random = myarray[Math.floor(Math.random() * myarray.length)];
document.getElementById("message").innerHTML=random;
}

function GetValue()
{
    var myarray= new Array("item1","item2","item3");
    var random = myarray[Math.floor(Math.random() * myarray.length)];
   document.getElementById("message").innerHTML=random;
}
<input type="button" id="btnSearch" value="Search" onclick="GetValue();" />
<p id="message" ></>


Solution

  • All you have to do is the create 2 more arrays and do the same thing to get a random word then concatenate them together. Like this:

    function GetValue() {
      var myarray1 = new Array("item1", "item2", "item3");
      var myarray2 = new Array("item4", "item5", "item6");
      var myarray3 = new Array("item7", "item8", "item9");
      var random1 = myarray1[Math.floor(Math.random() * myarray1.length)];
      var random2 = myarray2[Math.floor(Math.random() * myarray2.length)];
      var random3 = myarray3[Math.floor(Math.random() * myarray3.length)];
      var output = random1 + ' ' + random2 + ' ' + random3;
    
      document.getElementById("message").innerHTML = output;
    }
    <input type="button" id="btnSearch" value="Search" onclick="GetValue();" />
    <p id="message">
      </>