How to shuffle the elements in a JavaScript array

Short answer:

let list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list = list.sort(() => Math.random() - 0.5)

Long answer:

I need to rearrange the elements in the JavaScript array.

In other words, I want to remix the array elements so that their order is different from the previous order.

Start with an array like this:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Whenever I run the operation, I want something different, such as:

[4, 8, 2, 9, 1, 3, 6, 5, 7]
[5, 1, 2, 3, 7, 4, 9, 6, 8]
[3, 1, 4, 7, 8, 6, 2, 9, 5]

This is the process I came up with. Given arraylist:

const list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

We can call itsort()Method, this method accepts a function whose return value is between -0.5 and 0.5:

list.sort(() => Math.random() - 0.5)

Run this function on each element in the array. You can pass 2 elements of the array as follows:list.sort((a, b) => Math.random() - 0.5)But in this case, we don't use them. If the result of this operation is <0, then the elementaPlaced below the index belowb, and the opposite if the result is > 0.

you couldRead all the details about Array.sort() here.

callsort()The value on the list does not change the value of the original array.

Now you can assign the result of this operation to a new variable as follows:

const shuffled = list.sort(() => Math.random() - 0.5)

Or you can overwrite the existing list (if you declare asletChanging:

let list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list = list.sort(() => Math.random() - 0.5)

Download mine for freeJavaScript beginner's manual


More js tutorials: