Now and then, you randomly need to shuffle an array in
sort() method and pass a random number.
As mentioned in the introduction, we will be using the
sort method. In the end, we will have all items in a randomized order.
This method, without any parameters, will sort an array in a natural way like 123 and abc.
See the following example:
const charArray = ['d', 'f', 'a', 'c', 'b', 'e'];
const numArray = [1, 5, 3, 2, 4];
// ["a", "b", "c", "d", "e", "f"]
// [1, 2, 3, 4, 5]
As you can see, the Arrays get normalized sorted. But we can also pass a specific argument that we are going to use to randomize the array sorting.
const rockPaperScissor = ['💎', '📄', '✂️'];
console.log(rockPaperScissor.sort(() => 0.5 - Math.random()));
This will randomly shuffle the array. Let me explain in depth.
sort function compares two elements, where element one is bigger than two. It will put the index lower or higher.
As for the
.5 - Math.random() this will return a value between -0.5 and 0.5
So whenever the value is below 0, the element is placed before the other element. And otherwise, it will be positioned after the item.
Also, read about sorting an Array of Objects by Value
See the code example in this Codepen permalink
You can test this and see it in action on this Codepen.