Shuffling An Array

Randomizing elements is one of the most important things when you are creating a project. I'm going to illustrate how to shuffle an array using destructuring. First of all, you would need to create an array with your values and as a bonus, if you want to create an array with numbers order, you can create an array with empty values

let array = [];
array.length = 4;
Object.keys( Array.from(array) );

Then it will return an array with values from 1 to 4. Now let's start shuffling our array using this code.

Shuffle-Array-Code.webp

as you can see, at first we declared our variables which are currentIndex which is the last index (it will be updated every time) and the random variable which we will use later to get a random value from the array.

Second, we used a while loop with the array condition, so after we loop all over the array, the loop will stop.

Inside the loop, we redeclared the random variable and we set it to a random value within the array. After that, we decreased the currentIndex for two reasons. First to update the last index and the second which was to shrink the random range to exclude all the previous last indices.

Finally, we used the amazing destructuring feature to swap the variable. Look below to understand.

[1, 2, 3, 4 ] => [1, 4, 3, 2]

. Destructuring makes it way easier than storing a stash variable. Hope you found the blog useful.

Did you find this article valuable?

Support Ahmed Essam's blog by becoming a sponsor. Any amount is appreciated!