function shuffle(array) { const curIdx = array.length; // While there remain elements to shuffle... while (0 !== cur_idx) { // Pick a remaining element... const randIdx = Math.floor(Math.random() * curIdx); curIdx -= 1; // And swap it with the current element. const originalIdx = array[curIdx]; array[curIdx] = array[randIdx]; array[randIdx] = originalIdx; } return array; } // Usage of shuffle const arr = [1, 2, 3, 4, 5, 6]; arr = shuffle(arr); console.log(arr); // shorter function shuffle(array) { for (let i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var originalIdx = array[i]; array[i] = array[j]; array[j] = originalIdx; } } //es6 function shuffle_array(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter