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);

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

    return arr;

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

Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool



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];




Live demo for above code

Was this helpful?