×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Paul Zz
Added: Feb 20, 2017 5:30 PM
Modified: Feb 20, 2017 6:04 PM
Views: 10
Tags: array shuffle
ES6 ONLY.
Shuffles array in place.
  1. /**
  2.  * Suffles array in place.
  3.  * Input array is changed.
  4.  * @param {Array} arr
  5.  * @returns {Array|Boolean} Notice! Input and output arrays are the same.
  6.  */
  7. function shuffle(arr) {
  8.     if (!(arr instanceof Array)) {
  9.         return false;
  10.     }
  11.     for (let i = arr.length; i; i--) {
  12.         let rand = Math.floor(Math.random() * i);
  13.         [arr[i - 1], arr[rand]] = [arr[rand], arr[i - 1]];
  14.     }
  15.     return arr;
  16. }
  17.