Home > Web Front-end > JS Tutorial > How Can I Shuffle an Array in JavaScript?

How Can I Shuffle an Array in JavaScript?

Susan Sarandon
Release: 2024-12-19 12:07:27
Original
320 people have browsed it

How Can I Shuffle an Array in JavaScript?

Shuffling Arrays in JavaScript

In JavaScript, shuffling an array refers to rearranging its elements in a random order.

Fisher-Yates Shuffle Algorithm

The modern version of the Fisher-Yates shuffle algorithm can be implemented as:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}
Copy after login

ES6 Version

The ES6 version of the algorithm can be written as:

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}
Copy after login

Prototype Method

To make the function more versatile, it can be implemented as a prototype method for array:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: 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]];
        }
        return this;
    }
});
Copy after login

Usage Example

The following example demonstrates how to use the shuffle function:

const myArray = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
shuffle(myArray);
console.log(myArray); // Logs a shuffled array
Copy after login

The above is the detailed content of How Can I Shuffle an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template