Last active
September 27, 2023 09:52
-
-
Save tobiasroeder/bed9cbcae5d22ddda26e5300c688341c to your computer and use it in GitHub Desktop.
A way to mix an array in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For production use i recommend: https://phuoc.ng/collection/1-loc/shuffle-an-array/ | |
// function | |
function mixArray(array) { | |
let newArray = [], | |
maxRandNbr = array.length; | |
for (let i = 0; i = maxRandNbr; i++) { | |
randNbr = Math.round(Math.random() * (maxRandNbr - 1)); | |
let index = array.indexOf(array[randNbr]); | |
newArray.push(array[randNbr]); | |
array.splice(index, 1); | |
maxRandNbr--; | |
} | |
return newArray; | |
} | |
// example | |
var letters = [ | |
'A', | |
'B', | |
'C', | |
'D', | |
'E', | |
'F' | |
]; | |
console.log(mixArray(letters)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment