Home > Net >  how to display list cours randomly using angular?
how to display list cours randomly using angular?

Time:04-15

I have displayed a list of courses, but I want to display them randomly, and I don't know how to do it.

random.component.ts

export class RandomComponent implements OnInit {
  
  constructor() { }
  ngOnInit(): void {
  }
  courses:any[]=[
    'laravel','symfony','angular','react',
    'laravel1','symfony1','angular1','react1',
    'laravel2','symfony2','angular2','react2',
    'laravel3','symfony3','angular3','react3',
    'laravel4','symfony4','angular4','react4',
    'laravel5','symfony5','angular5','react5',
  ];

random.component.html

<div *ngFor="let cours of courses">
    {{ cours }}
</div>

CodePudding user response:

At file .ts you can use function to make an Array random.

function shuffle(array) {
let currentIndex = array.length,  randomIndex;
// While there remain elements to shuffle.
while (currentIndex != 0) {

// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;

// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
  array[randomIndex], array[currentIndex]];
  }
  return array;
}

courses = shuffle(courses);
  • Related