![]() |
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) shuffleThis 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
Output
[ 2, 4, 5, 1, 3 ] Using sort with Math.randomThe approach uses the `sort` function in combination with a custom comparison function which makes use of `Math.random()` for introducing randomness. When the array is effectively shuffled by subtracting random values, it is a result of the stability of the sorting algorithm. Example: The sort with Math.random method is applied in the following code to shuffle elements in an array in JavaScript. Javascript
Output
[ 1, 2, 4, 5, 3 ] Using array.map with Math.randomThis method shuffles an array effectively using Math.random(). The original value plus a randomly assigned number will be assigned as an element into an object in the `randomSort(array)` function. Sorting takes place depending on how much these numbers are randomly generated thereby leading to an array that is randomly sorted. Example: The following code shuffles elements in a JavaScript array by using the array.map with Math.random method. Javascript
Output
[ 4, 5, 1, 3, 2 ] Using array.reduce with Math.randomShuffling elements in an array by array.reduce and Math.random(). These functions accumulate new shuffled arrays that then change their element with randomly generated indices iteratively for every element in them.Shuffle array using reduce (array) thus swaps input array elements randomly. Example: The following code shuffles elements in a JavaScript array by using the array.reduce with Math.random method. Javascript
Output
[ 5, 2, 4, 3, 1 ] Using generator functionsThis technique implements a generator function that uses the Fisher-Yates (Knuth) Shuffle algorithm to shuffle an array. At every stage, the generator produces copies of the array thus preventing alterations to the original one. This makes it possible to get intermediate shuffled versions and a final completely shuffled array. Example: In the code below, elements are shuffled from a JavaScript array with the help of generator functions. Javascript
Output
[ 1, 2, 3, 4, 5 ] [ 1, 2, 4, 3, 5 ] [ 4, 2, 1, 3, 5 ] [ 4, 2, 1, 3, 5 ] [ 4, 2, 1, 3, 5 ] Final shuffled array: 4,2,1,3,5 |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |