Jan Hřídel

March 7, 2023

Array shuffling by Fisher-Yates algorithm

If you need to shuffle array of any objects, you can use the Fisher-Yates algorithm. The algorithm is very simple in principle.

const shuffleArray = (arr: any[]): any[] => {
  let currentIndex: number = arr.length;
  let randomIndex: number;

  // While there remain elements to shuffle.
  while (currentIndex !== 0) {
    // Pick a remaining element.
    randomIndex = Math.floor(Math.random() * currentIndex);

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

  return arr;

About Jan Hřídel

Full-stack web developer, web technology enthusiast, lecturer, team player as well as strong individual, daddy & family man.