0

Is there any way to randomize array values in a pipe while doing a *ngFor? I have found that someone uses ng-repeat but I think it is for previous versions (I am using Angular 8.3).

I have found this answer but it is using JS. I would like to use only Angular features if it is possible.

Thanks in advance.

1 Answers1

2

You can use the code from the link on your post on Typescript

shuffledArray:[]; 

shuffleArray(array) {
   var m = array.length, t, i;

   while (m) {    
    i = Math.floor(Math.random() * m--);
    t = array[m];
    array[m] = array[i];
    array[i] = t;
   }

  return array;
}

Now you can call this shuffleArray method on method like

ngOnInit(){
  this.shuffledArray = this.shuffleArray(array) // add your array as input
}

On your HTML you can loop

<div *ngFor="let item of shuffledArray">
{{item}}
</div>
Tzimpo
  • 964
  • 1
  • 9
  • 24
  • I'ts more compact use sort `this.array.sort((a,b)=>Math.random()<.5?-1:1)` – Eliseo Mar 21 '20 at 15:25
  • 1
    @Eliseo Do not use this method. It looks pretty, but isn't completely correct. Here are results after 10,000 iterations on how many times each number in your array hits index [0] (I can give the other results too): 1 = 29.19%, 2 = 29.53%, 3 = 20.06%, 4 = 11.91%, 5 = 5.99%, 6 = 3.32% – Tzimpo Mar 21 '20 at 16:37
  • GREAT! sure I didn't know (and I hope don't forget never), thanks – Eliseo Mar 21 '20 at 18:27
  • @Eliseo We are all here to learn from each other! – Tzimpo Mar 21 '20 at 18:33