javascript fisher yates shuffle mdn

Solutions on MaxInterview for javascript fisher yates shuffle mdn by the best coders in the world

showing results for - "javascript fisher yates shuffle mdn"
Finn
17 Oct 2020
1function shuffle(array) {
2  for (let i = array.length - 1; i > 0; i--) {
3    let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i
4
5    // swap elements array[i] and array[j]
6    // we use "destructuring assignment" syntax to achieve that
7    // you'll find more details about that syntax in later chapters
8    // same can be written as:
9    // let t = array[i]; array[i] = array[j]; array[j] = t
10    [array[i], array[j]] = [array[j], array[i]];
11  }
12}