Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Can anyone help me with this JavaScript program?

Hi,

I'm having trouble getting all of the quotes objects from my quotes array to appear without any duplicates until all have been displayed once ... the original forum post is here: https://teamtreehouse.com/community/random-quote-generator-not-returning-duplicate-quote

However I am unable to solve the duplicate issue, and an error displays in the console as well.

Thanks!

2 Answers

Alborz M. --Hey I updated the comment in the original post but I'll leave it here too for visibility.

Just need to change one small detail in your return statement. Since you've already saved the spliced object into the "splicedQuote" variable, you want to return that instead. Change it to:

// get random quote function that selects a random quote object from the quotes array
// and returns the randomly selected quote object
function getRandomQuote() {
    var theQuote = Math.floor(Math.random() * quotes.length);
    var splicedQuote = quotes.splice(theQuote, 1)[0];
    viewedQuotes.push(splicedQuote);
    if (quotes.length == 0) {
      quotes = viewedQuotes;
      viewedQuotes = [];
    }
    return splicedQuote;  // changed "quotes[theQuote]" to "splicedQuote"
}

here is a simple jsfiddle example.

Steven Parker
Steven Parker
243,656 Points

:white_check_mark: I was the first to provide a working solution for your original question. I'll repeat it here:

function getRandomQuote() {
  if (quotes.length == 0)                                       // if empty, reload the main list
    quotes = viewedQuotes.splice(0, viewedQuotes.length);       // (and empty viewed list)
  var theQuote = Math.floor(Math.random() * quotes.length);     // pick a quote at random
  var splicedQuote = quotes.splice(theQuote, 1)[0];             // take it out of the main list
  viewedQuotes.push(splicedQuote);                              // now add it to the "viewed" list
  return splicedQuote;                                          // return the chosen quote
}

:sparkles: