I want to shuffle an array of elements in JavaScript like these:
[0, 3, 3] -> [3, 0, 3]
[9, 3, 6, 0, 6] -> [0, 3, 6, 9, 6]
[3, 3, 6, 0, 6] -> [0, 3, 6, 3, 6]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use the modern version of the Fisher–Yates shuffle algorithm:
ES2015 (ES6) version
Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.
Use
Implementing prototype
Using
Object.defineProperty(method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such asfor (i in arr). The following will allow you to callarr.shuffle()to shuffle the arrayarr: