Summary of JS random shuffling array methods

  • 2021-06-29 10:10:40
  • OfStack

This paper summarizes the JS random shuffling method for arrays.Share it for your reference, as follows:

There are many ways to shuffle the array in JS. I think it is the most streamlined way to stream a method written by a foreigner on the Internet:


function randomsort(a, b) {
    return Math.random()>.5 ? -1 : 1;
    // use Math.random() Function Generation 0~1 Between random numbers and 0.5 Compare, Return -1 or 1
}
var arr = [1, 2, 3, 4, 5];
arr.sort(randomsort);

The sort() function is described here, and a function is built into the Array object in JS:


arrayobj.sort([sortfunction])

This method sorts the Array objects appropriately;New Array objects are not created during execution.

sortFunction is optional.

Is the name of the function used to determine the order of elements.If this parameter is omitted, the elements will be sorted in ascending order in ASCII character order.

The sortFunction method has two parameters.Represents two array items for each sort comparison.sort() performs this parameter back when comparing two array items each time it sorts and passes the two compared array items as parameters to the function.When a function returns a value of 1, it swaps the order of two array items, otherwise it does not.

We can modify the randomsort() above slightly to achieve ascending and descending ordering:


function asc(a,b) {
return a < b ? -1 : 1;// If a<b Do not swap, otherwise swap, that is, sort ascending 
}
function desc(a,b) {
return a > b ? -1 : 1;;// If a>b Don't swap, otherwise swap, sort in order 
}

In addition, an anonymous function can be placed directly in the call to the sort() method.The following are examples of odd numbers coming first and even numbers coming last, as follows:

Here are the reference fragments:


var arrA = [6,2,4,3,5,1];
arrA.sort( function(x, y) {
if (x % 2 ==0) return 1;
if (x % 2 !=0) return -1;
});
document.writeln(arrA); // Output: 1,5,3,4,6,2

More readers interested in JavaScript related content can view this site's topics: JavaScript Array Operation Skills Summary, JavaScript Switching Special Effects and Skills Summary, JavaScript Find Algorithmic Skills Summary, JavaScript Animation Special Effects and Skills Summary, JavaScript Errors and Debugging Skills Summary, JavaScript Data Structure and Algorithmic Skills Summary, andSummary of JavaScript Traversal Algorithms and Techniques and Summary of JavaScript Mathematical Usage

I hope that the description in this paper will be helpful to everyone's JavaScript program design.


Related articles: