There a lot of ways to shuffle array's elements in javascript
One of those ways is to loop through all the element and during each iteration try to generate a random index,
and using array destructuring we can replace each element with another one like the code below :
`function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
var arr=[1,2,3,4]
shuffle(arr)
console.log(arr) //Β [4, 1, 2, 3]
shuffle(arr)
console.log(arr) //[3, 1, 2, 4]
shuffle(arr)
console.log(arr) //[4, 3, 1, 2]
`
*Share your thoughts with me , Have a nice day
*
Top comments (0)