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

const xah_randomize_array = ((arr) => {
/* [ 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
] */
    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] ) );

Here's pre-ES2015 version:

// Fisher-Yates shuffle. can be used on array-like object
function xah_shuffle_array_inplace (myList) {
    var i = myList.length - 1;
    var j, temp;
    while (i >= 1) {
        j = Math.floor( Math.random() * ( i + 1 ) ); // random element up to i, inclusive
        // swap i j
        temp = myList[i];
        myList[i] = myList[j];
        myList[j] = temp;
        i--;
    }
    return myList;
}

console.log(
    xah_shuffle_array_inplace([1,2,3])
);

[see JS: Array How-To]

[see JS: Random Range Function]

Randomize DOM Element Children

JS: Randomize Element Children

Array Topic

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

  1. JS: Array Object
  2. JS: Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth