Custom sort : shuffle an array the quick way

PHOTO EMBED

Sat Jun 19 2021 07:10:34 GMT+0000 (Coordinated Universal Time)

Saved by @hisam #javascript #vanilla #sort #randomize #array

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const shuffledArray = array.sort((a, b) => 0.5 - Math.random());

// using Array map and Math.random
const shuffledArr = array => array.map(a => ({ sort: Math.random(), value: a })).sort((a, b) => a.sort - b.sort).map(a => a.value);

content_copyCOPY

As the function we pass to .sort() is looking for either a positive or negative number to either move the item ‘up’ or ‘down’ in the array, each item has a chance of being moved in either direction giving us a shuffled array of items. This works for a rough-and-ready approach but might not give you a truly random shuffle.