➤ How to Code a Game
➤ Array Programs in Java
➤ Java Inline Thread Creation
➤ Java Custom Exception
➤ Hibernate vs JDBC
➤ Object Relational Mapping
➤ Check Oracle DB Size
➤ Check Oracle DB Version
➤ Generation of Computers
➤ XML Pros & Cons
➤ Git Analytics & Its Uses
➤ Top Skills for Cloud Professional
➤ How to Hire Best Candidates
➤ Scrum Master Roles & Work
➤ CyberSecurity in Python
➤ Protect from Cyber-Attack
➤ Solve App Development Challenges
➤ Top Chrome Extensions for Twitch Users
➤ Mistakes That Can Ruin Your Test Metric Program
How to Shuffle Array in JavaScript? This tutorial will look at a few JavaScript methods for shuffling an array.
Adding a custom method to a.sort is the first and most straightforward approach to shuffle an array in JavaScript.
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const shuffledArray = array.sort((a, b) => 0.5 - Math.random());
console.log(shuffledArray)
Output:-
[ 8, 1, 7, 2, 9, 10, 3, 4, 5, 6 ]
Each item in the array has a chance of being moved in either direction, giving us a shuffled array of objects because the function we supply to.sort() looks for either a positive or negative value to either move the item “up” or “down” in the array.
This is effective for a crude method but might produce something other than a random shuffle. You may show that utilizing the custom sort function is wrong if you research the method mentioned above.
The Fisher-Yates algorithm must be used to shuffle an array with a truly random distribution of its elements.
Algorithm Fisher-Yates
Fortunately, it’s not too difficult:-
const shuffleArray = (array) => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
};
As you can see, all that is required is to loop around the array from beginning to finish, select a random item from the array, and swap it with the item currently in the iteration.
The code, as mentioned above, can shuffle an array in JavaScript and provide a different random result each time.
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!