How To Shuffle Arrays And Objects In JavaScript | Online Tool


Use the code snippet below to easily shuffle arrays and arrays of objects in your JavaScript projects. This tool uses a modern version of the Fisher-Yates (Knuth) shuffle algorithm for reliable randomization. Perfect for developers needing random array sorting functionality.

What is Array Shuffling?

Shuffling is the process of rearranging elements in an array into a random order. This is commonly used in applications like games, quizzes, data randomization, and more. In JavaScript, shuffling is often implemented using the Fisher-Yates algorithm, which ensures an unbiased and efficient randomization.

For example, if you have an array of numbers:

const numbers = [1, 2, 3, 4, 5];

After applying a shuffle function, the order might change to something like:

[3, 1, 5, 2, 4]

Since JavaScript does not provide a built-in shuffle() method, developers typically use a custom function, like the Fisher-Yates shuffle, to achieve this behavior.

Live Demo: Online Array Shuffle Tool

Enter your array (valid JSON format) and click the shuffle button:

Result:

JavaScript Shuffle Function

The following JavaScript function implements the Fisher-Yates (Knuth) shuffle algorithm to randomly shuffle an array. It includes important features such as input validation to ensure the function only accepts valid arrays, and an error check to prevent shuffling an empty array.

The function will take an array (or array of objects) and return a new array with the items shuffled:

JavaSctipt
// JavaScript Shuffle Function with Input Validation
const shuffleArray = (array) => {
    // Input validation
    if (!Array.isArray(array)) {
        throw new TypeError('Input must be an array');
    }
    // Immediately return a copy if the array has 0 or 1 elements
    if (array.length <= 1) {
        return array.slice();
    }
    // Make a copy if you don't want to modify the original array
    const shuffled = array.slice();
    // Iterate from the last element down to the second element
    for (let i = shuffled.length - 1; i > 0; i--) {
        // Generate a random index between 0 and i (inclusive)
        const j = Math.floor(Math.random() * (i + 1));
        // Swap elements at positions i and j
        const temp = shuffled[i];
        shuffled[i] = shuffled[j];
        shuffled[j] = temp;
    }
    return shuffled;
};

How to Use:

Basic Array Example

JavaSctipt
// Example usage with a simple array:
const numbers = [1, 2, 3, 4, 5];
console.log("Shuffled numbers:", shuffleArray(numbers));

Array of Objects Example:

JavaSctipt
// Example usage with an array of objects:
const people = [
  { name: "Surya", age: 25 },
  { name: "Sali", age: 30 },
  { name: "Kiran", age: 35 }
];
console.log("Shuffled people:", shuffleArray(people));

How to Use the Shuffle Function

  1. Copy the Code: Copy the provided shuffle function code snippet into your JavaScript file.
  2. Prepare Your Array: Define the array or array of objects that you want to shuffle.
  3. Call the Function: Use shuffleArray(yourArray) to get a new array with the items shuffled.
  4. Integrate into Your Project: Use the shuffled array as needed in your application.

Key Features

  • Works with both primitive values and objects
  • Implements Fisher-Yates shuffle algorithm
  • Maintains original array elements
  • Pure function implementation

Note: This implementation creates a shallow copy of the original array. For arrays containing complex objects, object references will be preserved.

Extending the JavaScript Array Prototype with a Shuffle Function

For an even more seamless experience when working with arrays, you can extend the Array prototype to include a shuffle method. This allows you to shuffle an array directly using the intuitive syntax [1, 2, 3, 4, 5].shuffle();. Below is a simple yet effective implementation using the Fisher-Yates algorithm:

JavaScript
// Add shuffle method to Array prototype
Array.prototype.shuffle = function() {
  for (let i = this.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [this[i], this[j]] = [this[j], this[i]]; // Swap elements
  }
  return this; // Return the shuffled array for chaining
};

Usage Examples:

Shuffling a Simple Array:

JavaSctipt
// Shuffling a Simple Array
const numbers = [1, 2, 3, 4, 5];
numbers.shuffle(); // Modifies the original array
console.log(numbers); // Example: [3, 1, 5, 2, 4]

The shuffle is performed in place, meaning that the original array is modified. If you need to preserve the original array, create a copy first (for example, using the spread operator: [...numbers].shuffle()).

Shuffling an Array of Objects:

JavaSctipt
// Shuffling an Array of Objects
const users = [
  { id: 1, name: "Jack" },
  { id: 2, name: "Olive" },
  { id: 3, name: "Lucas" }
];

users.shuffle();
console.log(users);

Generate and Shuffle a Range of Numbers

This function creates an array of numbers within a specified range (from start to end) and shuffles them using the unbiased Fisher-Yates shuffle algorithm. This is useful for generating randomized sequences, such as lottery numbers, randomized IDs, or quiz question orders.

JavaScript
// Generates an array of numbers within a specified range and shuffles it
const generateAndShuffleRange = (start, end) => {
    // Validate inputs
    if (typeof start !== "number" || typeof end !== "number") {
        throw new TypeError("Both start and end must be numbers.");
    }
    if (!Number.isFinite(start) || !Number.isFinite(end)) {
        throw new RangeError("Start and end must be finite numbers.");
    }
    if (start > end) {
        throw new RangeError("Start must be less than or equal to end.");
    }
    // Generate range
    const range = Array.from({length: end - start + 1 }, (_, i) => start + i);

    // Fisher-Yates Shuffle
    for (let i = range.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [range[i], range[j]] = [range[j], range[i]];
    }
    return range;
};

Example Usage:

JavaScript
// Example Usage
// Shuffled array of numbers from 1 to 10
console.log(generateAndShuffleRange(1, 10));

// Shuffled array of numbers from 5 to 15
console.log(generateAndShuffleRange(5, 15));

// Shuffled array of numbers from 100 to 105
console.log(generateAndShuffleRange(100, 105));

Shuffle Words in a Sentence

This function takes a sentence as input and randomly shuffles the words while maintaining the integrity of the sentence structure. This is useful for text manipulation, creating word games, or generating randomized text for testing purposes.

JavaScript
// Shuffles the words in a given sentence using the Fisher-Yates algorithm.
const shuffleSentence = sentence => {
    if (typeof sentence !== "string" || sentence.trim() === "") {
        throw new TypeError("Input must be a non-empty string.");
    }
    const words = sentence.trim().split(/\s+/); // Handles multiple spaces
    // Fisher-Yates Shuffle Algorithm
    for (let i = words.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [words[i], words[j]] = [words[j], words[i]];
    }
    return words.join(' ');
};

Example Usage:

Shuffling a Simple Sentence:

JavaScript
// Example Usage
const sentence = "JavaScript makes web development fun and powerful";
console.log(shuffleSentence(sentence));
// Output: "development JavaScript makes fun powerful and web" (Order will vary)

Shuffle with Seed for Predictable Results

This function allows you to shuffle an array deterministically using a seeded random number generator (Lehmer Linear Congruential Generator - LCG). This ensures that the same input array and seed will always result in the same shuffled output. It’s useful for testing, simulations, or any situation where reproducibility is important.

JavaScript
// Shuffles an array deterministically using a seeded random number.
const shuffleWithSeed = (array, seed) => {
    if (!Array.isArray(array)) {
        throw new TypeError("Input must be an array.");
    }
    if (typeof seed !== "number" || !Number.isFinite(seed)) {
        throw new TypeError("Seed must be a finite number.");
    }
    // Seeded PRNG using Lehmer random number generator (LCG)
    const seededRandom = () => {
        const a = 1664525,
            c = 1013904223,
            m = 2 ** 32; // LCG constants
        seed = (a * seed + c) % m;
        return seed / m;
    };
    const shuffled = [...array]; // Avoid mutating the original array
    let currentIndex = shuffled.length;
    // Fisher-Yates Shuffle using seeded RNG
    while (currentIndex > 0) {
        const randomIndex = Math.floor(seededRandom() * currentIndex);
        currentIndex--;
        [shuffled[currentIndex], shuffled[randomIndex]] = [shuffled[randomIndex], shuffled[currentIndex]];
    }
    return shuffled;
};

Example Usage:

JavaScript
// Example Usage
const array = [1, 2, 3, 4, 5];
const seed = 42;
console.log(shuffleWithSeed(array, seed));
// Output: [3, 5, 2, 1, 4] (Consistent with seed 42)

// Shuffling a String Array with a Seed
const array2 = ["apple", "banana", "cherry", "date"];
const seed2 = 123;
console.log(shuffleWithSeed(array2, seed2));
// Output: ["date", "apple", "banana", "cherry"] (Consistent with seed 123)

const firstShuffle = shuffleWithSeed([10, 20, 30, 40], 99);
const secondShuffle = shuffleWithSeed([10, 20, 30, 40], 99);
console.log(firstShuffle);
// Output: [30, 40, 20, 10]

console.log(secondShuffle);
// Output: [30, 40, 20, 10] (Same result as firstShuffle)

Note: Using a seed number ensures that the shuffled result is always the same for the same input. If you change the seed number, the shuffled output will be different, providing a new random order. This is useful for situations where you need consistent results across multiple runs or want to generate different variations by simply adjusting the seed.

What is the Fisher-Yates Shuffle Algorithm?

The Fisher-Yates Shuffle (also known as the Knuth Shuffle) is an efficient algorithm for randomly shuffling an array. It ensures each possible order of elements is equally likely, making it the best method for unbiased shuffling.

How Does the Fisher-Yates Algorithm Work?

The Fisher-Yates algorithm works by iterating through the array from the last element to the first. At each step, it selects a random element from the remaining unshuffled portion of the array and swaps it with the current element. This ensures that every element has an equal chance of ending up in any position.

Here is a step-by-step breakdown of the algorithm:

  1. Start from the last element in the array (i=array.length - 1).
  2. Generate a random index j between 0 and i (inclusive).
  3. Swap the element at index i with the element at index j.
  4. Decrement i by 1 and repeat the process until i reaches 0.

Why is Fisher-Yates Unbiased?

The Fisher-Yates algorithm is unbiased because every element in the array has an equal probability of being placed in any position. This is achieved by ensuring that the random selection at each step is made from the remaining unshuffled elements only. As a result, every possible permutation of the array is equally likely.

Example of Fisher-Yates in Action

Lets shuffle the array [1, 2, 3, 4, 5] using the Fisher-Yates algorithm:

  1. Start with i=4 (last element). Randomly pick j=2. Swap 5 and 3: [1, 2, 5, 4, 3].
  2. Move to i=3. Randomly pick j=1. Swap 4 and 2: [1, 4, 5, 2, 3].
  3. Move to i=2. Randomly pick j=0. Swap 5 and 1: [5, 4, 1, 2, 3].
  4. Move to i=1. Randomly pick j=1. No swap needed: [5, 4, 1, 2, 3].
  5. Move to i=0. The process is complete.

The final shuffled array is [5, 4, 1, 2, 3]. Each step ensures that the remaining elements are shuffled fairly.

Advantages of Fisher-Yates

  • Efficient: The algorithm runs in O(n) time, making it suitable for large arrays.
  • Unbiased: Every permutation of the array is equally likely.
  • In-Place: It shuffles the array in place, requiring no additional memory.

JavaScript Implementation

Here is the JavaScript implementation of the Fisher-Yates shuffle algorithm:

JavaScript
function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

This implementation is simple, efficient, and works for both primitive arrays and arrays of objects.