Shuffle an array in Javascript
Write a simple logic to shuffle a given array. Consider this array - const nums = [1, 2, 3, 4, 5, 6]; You can shuffle this array by using the following code - const nums = [1, 2, 3, 4, 5, 6]; nums.sort(() => Math.random() - Math.random()); console.log(nums); /* [ 1, 4, 5, 2, 6, 3 ] [ 6, 1, 4, 2, 5, 3 ] ... */ Each run of the routine will give you a different array, thanks to Math.random() expression. Subtracting one random number from the other can give you a positive or negative result - so the sort can be totally different and random. ...