JS: Random Array Element, Randomize Array

By Xah Lee. Date: . Last updated: .

Get a Random Element from Array

// return a random item of a array
const xah_get_random_array_item = ((ar) => ( ar[ Math.floor( Math.random() * ar.length ) ] ));

// test
const x = [1, 2, 3, 4, 5]
console.log ( xah_get_random_array_item( x ) );
console.log ( xah_get_random_array_item( x ) );
console.log ( xah_get_random_array_item( x ) );
console.log ( xah_get_random_array_item( x ) );
console.log ( xah_get_random_array_item( x ) );
console.log ( xah_get_random_array_item( x ) );

Randomize Array

/* [ Fisher-Yates shuffle. can be used on array-like object
Modify array inplace.
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;
});

// test
console.log( xah_randomize_array( [1,2,3,4,5,6] ) );

[see JS: Array How-To]

[see JS: Random Range Function]

Randomize DOM Element Children

JS: Randomize Node Children

JS Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. CSS
  3. JavaScript
  4. JS Obj Ref
  5. DOM
  6. SVG
  7. Blog