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
Joseph Frazer
5,404 PointsHow do I make sure they don't get the same fact twice?
How do I prevent the user from getting the same fact in a row?
let factButton = document.getElementById('factButton'),
factZone = document.getElementById('factZone'),
DYK = document.getElementById('DYK'),
facts = [
'The average person walks the equivalent of three times around the world in a lifetime.', 'Coca-Cola would be green if coloring wasn’t added to it.', 'You cannot snore and dream at the same time.', 'New York drifts about one inch farther away from London each year.'
];
function randomize() {
var randomNumber = Math.floor(Math.random() * facts.length);
console.log(randomNumber);
factZone.innerHTML = facts[randomNumber];
}
randomize();
factButton.addEventListener('click', () => {
randomize();
});
1 Answer
Steven Parker
243,318 Points
There are several ways to accomplish this, here are some options:
- keep a separate array of booleans indicating which items have been used, re-pick until an unused item is selected
- expand the data into an object array with both a string and "used" property for each, re-pick as above
- move the picked item to the end of the list, then reduce the available choice size by 1
- keep an entirely separate array for "picked" items, move each chosen one out of the source list to it
- just delete each item that has been chosen (only if you do not need to re-use the list!)
I prefer the last three methods to the first two, because each random choice is guaranteed to return a unique item and no retries are needed.