An Interest In:
Web News this Week
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
- March 14, 2024
Vanilla JavaScript Shuffle Array
Now and then, you need randomly to shuffle an array in JavaScript
. There is a super-easy way of doing so. We can use the sort()
method and pass a random number to it.
JavaScript Shuffle Array
As mentioned in the introduction, we are going to be using the sort
method.
This method, without any parameters, will sort an array in a natural way like 123 and abc.
See the following example:
var charArray = ['d', 'f', 'a', 'c', 'b', 'e'];var 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 normalised sorted. But we can also pass a specific argument which is what we are going to use to randomise the sort.
var rockPaperScissor = ['', '', ''];console.log(rockPaperScissor.sort(() => 0.5 - Math.random()));
This will randomly shuffle the array let me explain in depth.
The sort
function comes with a comparison between 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 one other element.
Also, read about sorting an Array of Objects by Value
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
Original Link: https://dev.to/dailydevtips1/vanilla-javascript-shuffle-array-558c
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To