 ### CopyPastor

Score: 1; Reported for: Exact paragraph match Open both answers

## Possible Plagiarism

Plagiarized on 2022-05-10
by Cristian Traìna

## Original Post

Original - Posted on 2012-09-28
by Laurens Holst

Use `splice` to remove the correct answer from the array, then shuffle, then use `splice` again to insert the element back:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js --> function shuffleArray(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]]; } }
const answerOptions = [ { answerText: 'A', isCorrect: false }, { answerText: 'B', isCorrect: false }, { answerText: 'C', isCorrect: true }, { answerText: 'D', isCorrect: false }, ]

<!-- end snippet -->

Here's a JavaScript implementation of the [Durstenfeld shuffle](http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm), an optimized version of Fisher-Yates:
/* Randomize array in-place using Durstenfeld shuffle algorithm */ function shuffleArray(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } }
It picks a random element for each original array element, and excludes it from the next draw, like picking randomly from a deck of cards.
This clever exclusion swaps the picked element with the current one, then picks the next random element from the remainder, looping backwards for optimal efficiency, ensuring the random pick is simplified (it can always start at 0), and thereby skipping the final element.
Algorithm runtime is `O(n)`. **Note** that the shuffle is done in-place so if you don't want to modify the original array, first make a copy of it with [`.slice(0)`].
--- ## *EDIT:* Updating to ES6 / ECMAScript 2015 The new ES6 allows us to assign two variables at once. This is especially handy when we want to swap the values of two variables, as we can do it in one line of code. Here is a shorter form of the same function, using this feature.
function shuffleArray(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]]; } }

: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/slice