How to shuffle an array randomly

Source: Internet
Author: User
Tags shuffle

There may be a need to randomly disrupt an array when using JavaScript, and we can use the sort method of the array and the math.random to randomly sort

Const ARR = [0.5- math.random ()] Console.log (arr)

The main use of math.random () to generate a random number with a size comparison of 0.5 to sort, if 0.5-math.random () is greater than or equal to 0, the array of two number of positions unchanged, less than 0 on the swap position.

At first glance this is the result of a random sort, but in fact this sort is not so random. Specific analysis can refer to this article.

A better approach is to use the Fisher–yates shuffle algorithm, which is used here in the following way

Const ARR = [1,2,3,4,5,6]array.prototype.shuffle=function() {  vari = This. Length, J, temp; if(i = = 0)return  This;  while( --i) {j= Math.floor (Math.random () * (i + 1 ) ); Temp= This[i];  This[I] = This[j];  This[j] =temp; }  return  This;} Arr.shuffle ()

Https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array

How to shuffle an array randomly

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.