JavaScript: Random Array Element, Randomize Array

By Xah Lee. Date: . Last updated: .

Get a Random Element from Array

/* [
xah_get_random_array_item(arr) return a random item of a array.
http://xahlee.info/js/javascript_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/javascript_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]

[see JS: Random Number Function]

Randomize DOM Element Children

Randomize Node Children

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc