This question has already been answered:

for (let i = 0; i < 6; i++) { // i=0; i<6 this.blocks.push({ colorIndex: Math.floor(Math.random() * 16 + 1), id: Math.random().toString(16).slice(2), }) } 

here is a cycle, colorIndex should load random numbers, but it happens that loads the same. each number is a specific color) I do not want the same sinkers. Tell me how to change the code that would not load the same. cubes only 6 pieces

Reported as a duplicate at Grundy. javascript Aug 23 '18 at 8:59 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • can make an array of valid values. mix it up. and take in the cycle the first 6, or how much you need there. - teran

3 answers 3

You can try it like this

 this.blocks = []; var numbers = []; for (var i; this.blocks.length < 6; i++) { // i=0; i<6 var randomNumber = Math.floor(Math.random() * 16 + 1); if (!numbers.includes(randomNumber)) { numbers.push(randomNumber) this.blocks.push({ colorIndex: randomNumber, id: Math.random().toString(16).slice(2), }) } } console.log(this.blocks) 

    You should use a while loop until the size of the array is 6. Inside we add a check for the existence of such an index in the array.

     const blocks = []; while (blocks.length <= 6) { const colorIndex = Math.floor(Math.random() * 16) + 1; const isExists = blocks.find((block) => block.colorIndex === colorIndex); if (isExists) continue; blocks.push({ id: Math.random().toString(16).slice(2), colorIndex }); } 

      as an addition to my comment, but the shuffle method is bad here.

       var data = [...Array(16).keys()] .sort( () => Math.random() - 0.5) .slice(0,5) .map( v => ({ colorIndex: v + 1, id: Math.random().toString(16).slice(2) } )) console.log(data); 

      • In addition, it is worth adding that with this mixing: .sort(()=>Math.random() - 0.5) not all results are equiprobable. - Yaant
      • @Yaant therefore it is written that mixing is bad - teran