1

How do I pull a string randomly from an array, and insert that string into a span? Heres the arrays:

var startupX = ['Uber', 'Google', 'Amazon', 'Apple', 'Facebook', 'Twitter'];
var startupY = ['Slack', 'Trello', 'Tesla', 'Hyperloop', 'Harvest'];

And these are the spans that a startup name needs to go into

<h1 id="xForY"></h1>
  <h1>A startup that is 
    <span id="startupX"></span>, but for 
    <span id="startupY"></span>
    </h1>
o.schiff.
  • 13
  • 5
  • Which part are you having trouble with? Is it just the random part, or do you not know how to insert *any* text into a span using JS? – nnnnnn Jul 05 '16 at 23:35
  • You can get your answer here: http://stackoverflow.com/questions/4550505/getting-random-value-from-an-array – pokemon Jul 06 '16 at 00:33

2 Answers2

1

First, find a random element from each of the arrays. Math.random() will help you with that.

Then you can use the DOM API to insert it into your page:

var startupX = ['Uber', 'Google', 'Amazon', 'Apple', 'Facebook', 'Twitter'];
var startupY = ['Slack', 'Trello', 'Tesla', 'Hyperloop', 'Harvest'];

var x = startupX[Math.floor(Math.random()*startupX.length)];
var y = startupY[Math.floor(Math.random()*startupY.length)];

document.getElementById('startupX').innerHTML = x;
document.getElementById('startupY').innerHTML = y;  
<h1 id="xForY"></h1>
<h1>A startup that is 
    <span id="startupX"></span>, but for 
    <span id="startupY"></span>
</h1>
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
  • This is great, to try and understand how it works tho-- innerHTML = x is taking the result of var x and replacing "startupX"? – o.schiff. Jul 05 '16 at 23:43
  • @OwenSchifferli It sets the *inner HTML* of the element with id `startupX` to the content of variable `x`. – TimoStaudinger Jul 06 '16 at 00:26
1

Math.random will give you a number from 0 inclusive to 1 exclusive [0, 1).

You can use that to get a random number that is within the max array index:

var randomIndex = Math.floor(Math.random() * startupX.length);

Then you can use this index to access your array:

startupX[randomIndex];

Having the value you can place it on the element:

document.getElementById('startupX').innerHTML = startupX[randomIndex];
BrunoLM
  • 97,872
  • 84
  • 296
  • 452