Home > Article > Web Front-end > Implementing the most efficient array shuffling method in JavaScript_javascript skills
Array reordering means disrupting the order of all elements in the array.
A common method is to pass a function into the native sort method of the array. This function randomly returns 1 or -1 to achieve the purpose of randomly arranging the array elements.
Although this method is intuitive, it is not very efficient. After my test, the time it takes to scramble an array of 10,000 elements is about 35ms (firefox)
I have always had the good quality of asking for answers, so I searched for an efficient method. See the original text here
This method adds a function to Array.prototype called shuffle - but the name is not important, what is important is its efficiency.
Take my above array of 10,000 elements to test. It only takes 7 or 8 milliseconds to complete the out-of-order operation using this method.
Increase the array elements 10 times to 100000 to test. The first sort method takes about 500 ms, and the shuffle method takes about 40 ms. The difference is huge.
Full test code:
//The following method is the most efficient
if (!Array.prototype.shuffle) {
Array.prototype.shuffle = function() {
for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j ] = x);
return this;
};
}
var t = new Date().getTime();
arr.shuffle();
document.write('
' arr '
');
var t1 = new Date().getTime();
document.write(t1-t);
In addition, have you noticed that the for loop in the shuffle code does not have the second half! That is, there is only for(..) but no {..} behind it. It can be written like this! And it actually executes normally! It’s curious, I have to go to the blog park and ask.