How to Randomise/shuffle array elements using JavaScript


How to Randomise/shuffle array elements using JavaScript

In this tutorial we will see how to randomise / shuffle an array in JavaScript.

To shuffle an array means changing the order in which the items are placed in the array.

For example, If we have a starting array like:

[1, 2, 3, 4, 5, 6]

and when we shuffle / randomise the array, the output will be like :

[5, 3, 1, 6, 4, 2] 
//OR
[2, 4, 6, 3, 5, 1]

So to create a function to shuffle our array we will be using JavaScript methods like Array.map() and Array.sort()and Math.random() methods.

Shuffle Array Using JavaScript Methods

First, lets create the array with numbers sorted numbers from 1 to 6.

const array =  [1, 2, 3, 4, 5, 6]

And now let write a simple function with the power of JavaScript engine to shuffle array and print in on the console.log( ).

let arr = [1,2,3,4,5,6]

function shuffleArr(array){
  return array
  .map((value) => ({ value, sort: Math.random() }))
  .sort((a, b) => a.sort - b.sort)
  .map(({value})=> value)
}

console.log(shuffleArr(arr))

In the above code, we have first map each item in the array in an object and gave a sort key to it.

The value of the sort key is randomly generated by Math.random() function.

The sort() method is then use to sort the items according to the random value of the sort key.

At last we have again map each items of the sorted array and just returned the value.

Shuffle Array using Lodash Library.

Lodash is a JavaScript library that provides us with some utility functions for our common programming task.

Lodash provide us with a shuffle function that can easily randomise an array without the need of writing the whole shuffle function as above.

You can install Lodash using NPM or use the cloudflare CDN.

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script> 

Once done just use the _.shuffle() method on your array like this:

const array =  [1, 2, 3, 4, 5, 6]
randomizedArr = ._shuffle(array)
console.log(randomizedArr)

Related Topics:

Quick Way To Reverse An Array In JavaScript

Retrieve Random Item From An Array In JavaScript

How To Sort An Array Alphabetically In Javascript?