-2

Goal: When the page loads you get 5 quotes taken from an array at random. The quotes should not be the same/overlap. I've been able to have one quote generate at random with the code below. The thing I cannot figure out is how to display multiple random quotes without having them repeat.

My problem is even when I display the results of math.random several times it is the same random quote --for example the page will load the random quote "#1" and display that quote 5 times instead of 5 random different quotes.

Current JS code:

var quotes = ['Quote 1', 'Quote 2', 'Quote 3', 'Quote 4', 'Quote 5', 'Quote 6', 'Quote 7', 'Quote 8', 'Quote 9', 'Quote 10'];
var quote = quotes[Math.floor(Math.random()*quotes.length)];

var result = document.querySelector("#quoteOne");
result.textContent = (quote);
<p id="quoteOne"></p>
GG.
  • 21,083
  • 14
  • 84
  • 130
AndrewLeonardi
  • 3,351
  • 9
  • 47
  • 100

1 Answers1

0

If you consider using Lodash, this could be solved with _.sample

var randomQuote = _.sample(quotes);

DEMO

GG.
  • 21,083
  • 14
  • 84
  • 130
  • 1
    Because this doesn't really answer the question. You're just deferring the work to a library. If they were asking how to do this "using Lodash" or gave any other indicator that they were already using Lodash then I'm sure you'd be fine. – Mike Cluck Apr 18 '16 at 23:09
  • 1
    I don't agree, OP didn't refuse third-party libraries and he might not know that something like Lodash exists and solves his problem in keeping his code well written and tested. There are several discussions about that on Meta (e.g. http://meta.stackoverflow.com/questions/318411/answers-which-assume-use-of-third-party-libraries) – GG. Apr 19 '16 at 00:23
  • 1
    I'm with @GG. on this. Particularly with the NPM leftpad debacle, Lodash has been frequently discussed as a sort-of "standard library" for JS. – ceejayoz Apr 19 '16 at 00:33