## DEV Community is a community of 700,720 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Discussion on: How to shuffle an array in JavaScript

## Replies for: Is the first method really flawed? Also, rather than Math.random(), I can always use crypto.getRandomValues() developer.mozilla.org/en-US/docs/W...

James Bubb

Yeah, apparently - I think it boils down to a question of `sort()` having a strong bias for keeping elements in their initial positions (there's a bit of a discussion about it on one of the answers here: stackoverflow.com/questions/245095...).

Thanks for the tip regarding `.getRandomValues()`. How would that work with strings or objects?

Pacharapol Withayasakpunt • Edited

I read the solution part of javascript.info/array-methods#shuf..., but not really understand the logic, or is it the fault of JS Engine?

For `.getRandomValues()`, there are two more methods of shuffling, but of course, not performant, even if your first method is not faulty.

``````function shuffle1(arr: any[]): any[] {
return Array(arr.length).fill(null)
.map((_, i) => [Math.random(), i])
.sort(([a], [b]) => a - b)
.map(([, i]) => arr[i])
}

function shuffle2(arr: any[]): any[] {
const ord = new Uint8Array(arr.length)
crypto.getRandomValues(ord)

return ord
.map((a, i) => [a, i])
.sort(([a], [b]) => a - b)
.map(([, i]) => arr[i])
}
``````
Haha! I like this from that site: `But due to the utter randomness of the comparison the black box goes mad, and how exactly it goes mad depends on the concrete implementation that differs between engines.`