JS: Random Array Element, Randomize Array 🚀
Get a Random Element from Array
/* xah_get_random_array_item(arr) return a random item of a array. http://xahlee.info/js/js_random_array.html Version 2020-10-01 */ const xah_get_random_array_item = ((ar) => (ar[Math.floor(Math.random() * ar.length)]));
Randomize Array
/* xah_randomize_array(arr) Fisher-Yates shuffle array elements, return it. Modify array inplace. Can be used on array-like object. http://xahlee.info/js/js_random_array.html version 2017-09-18 */ const xah_randomize_array = ((arr) => { let i = arr.length - 1; let j; while (i >= 1) { // random element up to i, include i j = Math.floor(Math.random() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; i--; } return arr; });
〔see Array How-To〕