Skip to content

Instantly share code, notes, and snippets.

@tobiasroeder
Last active September 27, 2023 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobiasroeder/bed9cbcae5d22ddda26e5300c688341c to your computer and use it in GitHub Desktop.
Save tobiasroeder/bed9cbcae5d22ddda26e5300c688341c to your computer and use it in GitHub Desktop.
A way to mix an array in JavaScript.
// 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