DEV Community

Cover image for Javascript Polyfill Array.shuffle #6
chandra penugonda
chandra penugonda

Posted on • Edited on

Javascript Polyfill Array.shuffle #6

This problem was asked by Tencent.

How would you implement a shuffle() ?

Shuffle the array, it may be [1, 3, 2, 4], but it should modify the array inline to generate a randomly picked permutation at the same probability.

Example

[1, 2, 3, 4].shuffle()
Enter fullscreen mode Exit fullscreen mode

Solution


if (!Array.prototype.shuffle) {
  Array.prototype.shuffle = function shuffle() {
    let i = this.length - 1;
    while (i) {
      const j = Math.floor(Math.random() * (i + 1));
      [this[i], this[j]] = [this[j], this[i]];
      i--;
    }
    return this;
  };
}

Enter fullscreen mode Exit fullscreen mode

This works by:

  • Checking if Array.prototype.shuffle() already exists
  • If not, adding a shuffle() method to the Array prototype
  • The shuffle() method:
  • Loops from the array length down to 0
  • Picks a random index between 0 and i
  • Swaps the current element (i) with the random element (j)
  • This shuffling procedure is performed in place on the array
  • The shuffled array is returned

This polyfill implements a simple shuffle algorithm to randomly rearrange the elements of an array.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay