Vanilla JavaScript Shuffle Array

โœ๏ธ

Learn how to randomly shuffle the item in an array. We will have a random order of items afterwards. See the code example on Codepen.

21 Jun, 2020 ยท 2 min read

Now and then, you randomly need to shuffle an array in JavaScript. There is a super-easy way of doing it. We can use the sort() method and pass a random number.

So in today's tutorial, I will teach you how to shuffle an array in Javascript.

JavaScript Shuffle Array

As the introduction mentions, we will use the sort method. In the end, we will have all items in a randomized order.

This method, without any parameters, will sort an array naturally like 123 and ABC.

See the following example:

const charArray = ['d', 'f', 'a', 'c', 'b', 'e'];
const numArray = [1, 5, 3, 2, 4];

console.log(charArray.sort());
// ["a", "b", "c", "d", "e", "f"]

console.log(numArray.sort());
// [1, 2, 3, 4, 5]

As you can see, the Arrays get normalized and sorted. But we can also pass a specific argument that we will use to randomize the array sorting.

const rockPaperScissor = ['๐Ÿ’Ž', '๐Ÿ“„', 'โœ‚๏ธ'];
console.log(rockPaperScissor.sort(() => 0.5 - Math.random()));

This will randomly shuffle the array. Let me explain in depth.

The sort function compares two elements, where element one is bigger than two. It will put the index lower or higher.

As for the .5 - Math.random() this will return a value between -0.5 and 0.5

So whenever the value is below 0, the element is placed before the other element. And otherwise, it will be positioned after the item.

Also, read about sorting an Array of Objects by Value

See the code example in this Codepen

You can test this and see it in action on this Codepen.

See the Pen Vanilla JavaScript Shuffle Array by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API