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 JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Accessing Items in an Array

Mark Libario
Mark Libario
9,003 Points

Whats a good condition to stop my numbers from repeating?

How would you right the conditional statement that would prevent the same numbers from being drawn?

a fellow treehouser mentioned something about listing all the items in the array already, and then removing it from the array every time it's drawn. But what if I want to do it in a different way and just use conditionals?

Is this possible and how would it be done?

Thanks!

/*
let lottoNumbers = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
  31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  41, 42, 43, 44, 45, 46, 47, 48, 49
];


let html = " ";

for ( let i = 1; i <7; i++) {
  var randomDraw = lottoNumbers [Math.floor(Math.random() * lottoNumbers.length)];
  html += "<div>";
  html += randomDraw ;
  html += "</div>";

}
document.write(html);
*/

function Lotto (number) {
  this.number = number;
  this.drawNumber = Math.floor(Math.random() * number) +1;


}


let html = "";


for (let i = 0 ; i < 6; i+= 1) {
  let draw = new Lotto(49);
  html += "<div>" + draw.drawNumber + "</div>";
}
document.write (html);

Here are two ways of doing it using objects and arrays.

1 Answer

Steven Parker
Steven Parker
231,269 Points

I believe it was me who suggested removing the picked items from the array. And I don't know a way to use a conditional to prevent the random selection from being duplicated — I will be most interested if someone else posts one!

But removing the picked items from the array would only take a small modification to what you have already (in the commented area), and it guarantees each pick will be different:

for (let i = 1; i < 7; i++) {
  var pick = Math.floor(Math.random() * lottoNumbers.length);
  html += "<div>" + lottoNumbers[pick] + "</div>";
  lottoNumbers.splice(pick, 1);  // remove the picked item from the array
}
Mark Libario
Mark Libario
9,003 Points

Yes steven! Thank! You've always been helpful! Im also interested in different ways on how this could be done haha.

Thanksss!