GustavoA GustavoA - 2 years ago 51
TypeScript Question

Generating an array without repeats in angular 2

I'm, trying to create an array of six, and it must not have any repeating numbers from 1 to 60.

My code right now its like this:

if(this.random.length != 0){
for(var u=0; u<6; u++){
this.y = Math.ceil(Math.random()*59+1);
for (var r of this.random){
if(r != this.y){
this.random.sort(function(a, b){return a-b});
return this.random;

It should check if the array has more then 0 elements, if it does it'll empty it.
if it's empty it'll assemble the array...
And it should not repeat numbers...
This works up to the point that I insert the repeating checker..:

for(var r of this.random)
if(r != this.y){

This guy makes my code stop working.

After searching I read something about the Fisher-Yates Shuffle technique, but it doesn't seems to work for me.

I'm using angular 2, with the Ionic 2 framework.

Does someone here have come up with this already?

Answer Source

This is what my code looks now. Working!

jogar(){ = [];
    this.numeros = [];  
    for(var i=0;<6;i++){ =;           
        var novoNumero=Math.floor((Math.random()*59)+1);            
        var verificacao=this.confereSeArrayContemItem(,novoNumero);       
        },b){return a-b});      
    console.log(,b){return a-b}));

confereSeArrayContemItem(array, item){
    var resultado = 0;
    for(var i=0;i<array.length;i++){
            resultado =1;
    return resultado;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download