Shuffling is a common operation in programming that is used to introduce randomness. In this article, we will look into some easy methods to shuffle an array in JavaScript.
4 Methods to Shuffle an Array in JavaScript
Arrays are linear data structures that store homogenous data, i.e. same type of data. An array can contain all integers, all characters, or all strings as the elements.
Shuffling an array is the process of reordering the elements within the array randomly. After shuffling, the elements are rearranged in a random order that is different from the original order of the array. There are various reasons why we need to shuffle arrays in programming:
- Randomization can help in designing games, statistical sampling, as well as in cryptography.
- Sometimes in algorithms, having a predictable order of elements results in biases. Shuffling helps to remove those biases.
- It can be useful during testing and debugging to test that the program gives correct output under different permutations of input data.
let’s now look into methods to shuffle an array. Let us get started!
1) Fisher-Yates Algorithm
Fisher-Yates Algorithm is a popular algorithm for shuffling an array in JavaScript. It is also called Knuth Shuffle. In it, we iterate over the array in reverse order and swap each element with a random one from the remaining unshuffled portion of the array.
Check the example below:
//declaring an array let arr=[1,2,3,4,5]; //shuffling an array for(let i=arr.length-1;i>0;i--){ const u=Math.floor(Math.random()*(i+1)); //swapping two elements [arr[i],arr[u]]=[arr[u],arr[i]]; } //printing the shuffled array for(let i=0;i<arr.length;i++){ console.log(arr[i]); }
Output:
3
2
4
5
1
In this example, we declared an array and used the Math.random() function to use random indices and swap them with current ones. In this way, we shuffled the array. We have obtained the desired output.
2) Using Underscore.js Library
Underscore.js is one of the libraries of JavaScript that have built-in functions such as shuffle functions. It provides an easy way to shuffle arrays without implementing the shuffling logic.
Let us see an example using the Underscore.js library:
//importing the underscore library const _ = require('underscore'); //declaring an array let arr=[1,2,3,4,5]; //shuffling an array const shuffledArr = _.shuffle(arr); //printing the shuffled array for(let i=0;i<arr.length;i++){ console.log(shuffledArr[i]); }
Output:
5
3
1
4
2
In this example, we have imported the library Underscore and used the shuffle function to shuffle or randomize the array. We have obtained the desired result.
3) Using Lodash Library
Lodash is another one of the JS libraries that have built-in functions such as shuffle functions. It provides an easy way to shuffle arrays without implementing the shuffling logic. Note that the shuffle function of the Lodash Library uses the Fisher-Tates Algorithm.
Let us see an example:
//importing the Lodash library const _ = require('Lodash'); //declaring an array let arr=[1,2,3,4,5]; //shuffling an array const shuffledArr = _.shuffle(arr); //printing the shuffled array for(let i=0;i<arr.length;i++){ console.log(shuffledArr[i]); }
Output:
3
2
5
4
1
In this example, we have imported the library Lodash and used the shuffle function to shuffle or randomize the array. We have obtained the desired result. The array is printed in a shuffled manner.
4) Drustenfield Shuffle Algorithm
The Drustenfield Shuffle Algorithm is another algorithm for this purpose. It is an optimized version of the Fisher-Yates Algorithm.
This algorithm selects a random value for each array index and excludes the selected value from the next pick. The Drustenfield Shuffle Algorithm also works in the backward direction. It also has a time complexity of O(N). It was designed before the Fisher-Yates algorithm.
Let us take an example.:
//declaring an array let arr=[1,2,3,4,5]; //shuffling an array for(let i=arr.length-1;i>0;i--){ const u=Math.floor(Math.random()*(i+1)); //swapping two elements let temp = arr[i]; arr[i] = arr[u]; arr[u] = temp; } //printing the shuffled array for(let i=0;i<arr.length;i++){ console.log(arr[i]); }
Output:
5
2
3
4
1
In this algorithm, we have used the Drustenfield Algorithm to shuffle the array. This method was used before es6. We have obtained the desired result.
Also, learn how to sort an array of objects in JavaScript using different approaches.
Conclusion
In this article, we learned how to shuffle an array in JavaScript. We can use the Fisher-Yates Algorithm, Drustenfield Algorithm, or libraries like Underscore or Lodash to shuffle an array. Try practicing different methods on different arrays and choose the suitable one according to your requirements.