-2

I have the following array:

var numbers = [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];

I want to get 15 random numbers from this array, where there can't be duplicates. I have no idea on how to do it.

Also, if it'd be easier, I would like to know if there is a way to generate an array with 15 numbers from 1 to 35, with no duplicates, instead of picking them from the array I showed.

Thanks in advance!

  • 1
    Do you know how to pick a random item from your array ? If you do it multiple times and remove it from your array every time, you should have your fifteen numbers without duplicates – Axnyff Jan 02 '19 at 23:37
  • The best answer in this question might come in handy as well: https://stackoverflow.com/questions/2380019/generate-unique-random-numbers-between-1-and-100 – claudiatc85 Jan 02 '19 at 23:51
  • Reading the last part of the post, it's not a duplicate of the linked questions. – Mulan Jan 03 '19 at 00:00

2 Answers2

1

If you are just trying to get a number between 1 and 35 then you could do this,

Math.floor(Math.random() * 35) + 1

Math.random() returns a number between 0 and 1, multiplying this by 35 gives a number between 0 and 35 (not inclusive) as a float, you then take a floor add 1 to get the desired range.

You can then loop over this and use this to populate your array.

If you don't want any repeats then I recommend you look at using a Set to make sure you don't have any repeats, then just loop until the set has the desired number of values.

Sets are documented here

tmcnicol
  • 576
  • 3
  • 14
0

Here is a simple method,.

First create the array of numbers from 1 to 35.

Then randomly delete one from this array until the length is equal to 15.

const nums = Array.from(new Array(35),(v,i)=>i+1); 
while (nums.length > 15) nums.splice(Math.random() * nums.length, 1);
console.log(nums.join(", "));
Keith
  • 22,005
  • 2
  • 27
  • 44