Search code snippets, questions, articles...

Methods to shuffle an array using javascript

In this post, we are going to explain different methods that can be used to shuffle an array in javascript. We will be randomizing the array and putting the array elements in different orders each time the function is executed.
function random_array(arr) {
    let idx = arr.length, random_num;

    while (idx != 0) {
        random_num = Math.floor(Math.random() * idx);
        idx--;

        [arr[idx], arr[random_num]] = [
            arr[random_num], arr[idx]];
    }

    return arr;
}

// Test the code
const result = random_array([10, 20, 30, 40, 50]);

console.log(result);
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

Output

[50,10,20,30,40]

Live demo for above code

Example 2: Use Array.sort() and Math.random() to shuffle array

Here we are using javascript functions Array.sort() and Math.random() to randomize an array.

Code Example

const arr_shuffle = (arr) => arr.sort(() => Math.random() - 0.5);

const my_array = [10, 20, 30, 40, 50, 60, 70];

console.log(arr_shuffle(my_array));

Output

[50,30,60,20,10,40,70]

Live demo for above code

Was this helpful?
0 Comments