How to use Fisher-Yates (Knuth) shuffle In Javascript
This algorithm, also known as the Knuth Shuffle, involves iterating through the array in reverse order and swapping each element with a randomly selected element that comes before it.
Example: The provided code uses the Fisher-Yates (Knuth) shuffle method to shuffle elements in a JavaScript array.
Javascript
function fisherYatesShuffle(arr) { for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; } return arr; } const arr1 = [1, 2, 3, 4, 5]; const shuffledArr1 = fisherYatesShuffle([...arr1]); console.log(shuffledArr1); |
Output
[ 2, 4, 5, 1, 3 ]
How to Shuffle the Elements of an Array in JavaScript ?
Shuffling arrays is an elementary operation in programming that helps to introduce change into data sets. There are several approaches in JavaScript using which one can shuffle the elements of the array which are as follows:
Table of Content
- Using Fisher-Yates (Knuth) shuffle
- Using sort with Math.random
- Using array.map with Math.random
- Using array.reduce with Math.random
- Using generator functions
Contact Us