Bummer! You must be logged in to access this page.

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

create random numbers with out them repeating in javascript

Basically I want to create random numbers up to 10. and put them in an array, but i dont want any of the numbers to repeat.

I have been stuck on this one for a long time

1 Answer

Hi, not sure quite what you're trying to achieve but here are a few ideas that will hopefully get you started in the right direction:

  • first step, declare an empty array to store each number in i.e. var numbersArray = []
  • declare a count variable which will be used to store the count of numbers in the array in the following while loop i.e. var i = 0;
  • next, setup the while loop where the counter condition is set to check the max length of the numbers array i.e. while (i <= 10) { /* Statements will go here */ } (alternatively max count will be lower, if you don't want to add all 10)
  • inside the loop, declare a new variable to store a temporary random number (it will be destroyed and recreated each time the loop is run) i.e. var number = Math.floor((Math.random() * 10) + 1);
  • next, also inside the loop after the above line, create an if statement where the checked condition is if numbersArray does NOT contain the number variable i.e. if (!numbersArray.includes(number)) { /* Statements will go here */ }
  • last, inside of the if statement - when it evaluates to true - push the randomly generated number to the array and increment the loop counter i.e. numbersArray.push(number); i++;