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

How Can I Efficiently Shuffle an Array in JavaScript?

DDD
Release: 2024-12-19 02:56:09
Original
601 people have browsed it

How Can I Efficiently Shuffle an Array in JavaScript?

Shuffling Arrays with JavaScript

The Fisher-Yates shuffle algorithm offers an effective method for shuffling arrays in JavaScript. By randomly swapping elements, it guarantees that each possible ordering has an equal chance of occurring.

Algorithm Implementation

The Fisher-Yates shuffle algorithm can be implemented as follows:

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

This algorithm iterates through the array in reverse order, swapping each element with a random element ahead of it in the array. The resulting array is shuffled due to the random nature of the swaps.

Usage

The shuffle function can be used to shuffle an array using the following syntax:

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);
Copy after login

ES6 Version

The Fisher-Yates algorithm has been optimized in ES6:

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

Implementation Prototype

This algorithm can be implemented as an array prototype method to facilitate direct shuffling of arrays:

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

This implementation allows arrays to be shuffled using the arr.shuffle() syntax.

The above is the detailed content of How Can I Efficiently 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template