Skip to content
Fix Code Error

How to randomize (shuffle) a JavaScript array?

March 13, 2021 by Code Error
Posted By: Anonymous

I have an array like this:

var arr1 = ["a", "b", "c", "d"];

How can I randomize / shuffle it?

Solution

The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle.

See https://github.com/coolaj86/knuth-shuffle

You can see a great visualization here (and the original post linked to this)

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

// Used like so
var arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);

Some more info about the algorithm used.

Answered By: Anonymous

Related Articles

  • Replace numbers with words? Fisher-Yates randomization
  • Dynamically update values of a chartjs chart
  • What is the copy-and-swap idiom?
  • Ember.js: rendering google chart in template (AKA target DOM…
  • Using Computed Properties inside Methods in vueJs
  • Vue How to Merge Two Arrays From Same Object?
  • How to generate a random string of a fixed length in Go?
  • Searching for matching elements between 2 arrays in C
  • Peak signal detection in realtime timeseries data
  • Reference - What does this regex mean?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

What’s the difference between SCSS and Sass?

Next Post:

How can I initialise a static Map?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error