a shuffle function that doesn't change the source array
Update: Here I'm suggesting a relatively simple (not from complexityDisclaimer perspective) and short algorithm
Please note that will do just fine with small sizedthis solution is not suitable for large arrays! If you are shuffling large datasets, but it's definitely going to cost a lot more than the classic Durstenfeld algorithm when you deal with huge arrays. You can findshould use the Durstenfeld in one of the top replies to this questionalgorithm suggested above.
Original answer:
If you don't wish your shuffle function to mutate the source array, you can copy it to a local variable, then do the rest with a simple shuffling logicSolution.
function shuffle(array) {
var result = [], source = array.concat([]);
while (source.length) {
let index = Math.floor(Math.random() * source.length);
result.push(source[index]);
source.splice(index, 1);
}
return result;
}
function shuffle(array) {
const result = [], itemsLeft = array.concat([]);
while (itemsLeft.length) {
const randomIndex = Math.floor(Math.random() * itemsLeft.length);
const [randomItem] = itemsLeft.splice(randomIndex, 1); // take out a random item from itemsLeft
result.push(randomItem); // ...and add it to the result
}
return result;
}
Shuffling logic: pick up a random index, then add the corresponding element to the result array and delete it from the source array copy. Repeat this action until the source array gets emptyHow it works.
And if you really want it short, here's how far I could get:
function shuffle(array) {
var result = [], source = array.concat([]);
while (source.length) {
let index = Math.floor(Math.random() * source.length);
result.push(source.splice(index, 1)[0]);
}
return result;
}
copies the initial
arrayintoitemsLeftpicks up a random index from
itemsLeft, adds the corresponding element to theresultarray and deletes it from theitemsLeftarrayrepeats step (2) until
itemsLeftarray gets emptyreturns
result