Last active
July 11, 2021 21:24
-
-
Save HallexCosta/e24bd90f714daf4bd3609e8cb3e705b7 to your computer and use it in GitHub Desktop.
Shuffle and Return Last 4 Elements
This file contains hidden or 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
function shuffle(array, amount = undefined) { | |
var m = array.length, t, i; | |
// While there remain elements to shuffle… | |
while (m) { | |
// Pick a remaining element… | |
i = Math.floor(Math.random() * m--); | |
// And swap it with the current element. | |
t = array[m]; | |
array[m] = array[i]; | |
array[i] = t; | |
} | |
if (amount <= arr.length) { | |
return array.slice(-(amount - arr.length)) | |
} | |
return array; | |
} | |
// Used like so | |
var arr = [2, 11, 37, 42]; | |
arr = shuffle(arr, 4) | |
console.log(arr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
References:
https://bost.ocks.org/mike/shuffle/
https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array