Shuffling Arrays with Fisher-Yates Algorithm

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the Fisher-Yates algorithm and its implementation in JavaScript. Specifically, we will be focusing on shuffling arrays using this algorithm. By the end of this lab, you will have a better understanding of how the Fisher-Yates algorithm works and how it can be used to randomize the order of elements in an array.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28615{{"`Shuffling Arrays with Fisher-Yates Algorithm`"}} javascript/data_types -.-> lab-28615{{"`Shuffling Arrays with Fisher-Yates Algorithm`"}} javascript/arith_ops -.-> lab-28615{{"`Shuffling Arrays with Fisher-Yates Algorithm`"}} javascript/comp_ops -.-> lab-28615{{"`Shuffling Arrays with Fisher-Yates Algorithm`"}} javascript/loops -.-> lab-28615{{"`Shuffling Arrays with Fisher-Yates Algorithm`"}} javascript/array_methods -.-> lab-28615{{"`Shuffling Arrays with Fisher-Yates Algorithm`"}} javascript/spread_rest -.-> lab-28615{{"`Shuffling Arrays with Fisher-Yates Algorithm`"}} end

Array Shuffling Algorithm

To shuffle an array in JavaScript, use the Fisher-Yates algorithm. This algorithm reorders the elements of the array randomly and returns a new array.

To start practicing coding, open the Terminal/SSH and type node.

Here's the code for the Fisher-Yates algorithm:

const shuffle = ([...arr]) => {
  let m = arr.length;
  while (m) {
    const i = Math.floor(Math.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  return arr;
};

To shuffle an array, pass the array to the shuffle function and it will return the shuffled array. For example:

const foo = [1, 2, 3];
shuffle(foo); // returns [2, 3, 1], and foo is still [1, 2, 3]

Summary

Congratulations! You have completed the Shuffle Array lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like