JavaScript’s missing shuffle method

Kevin Ebaugh
2 min readSep 21, 2021

--

As part of my end-of-Phase-1 project at Flatiron school, I wanted to show a list of locations. I wanted to show it in random order (instead of alphabetically), so I figured I could find a super handy Array.shufflemethod somewhere in JavaScript. I was wrong!

Most of my previous programming experience has been with Ruby, and I got used to Ruby’s shuffle method:

orderly_array = [1,2,3,4,5,6]
disorderly_array = orderly_array.shuffle
puts disorderly_array
=> [4,3,2,6,1,5]

(more at https://apidock.com/ruby/Array/shuffle)

After Googling around, I started to worry that there wasn’t an equivalent in JavaScript:

Screenshot of Google search “javascript array shuffle”

Compare to Googling the Ruby equivalent:

A shuffle method as the second result! 😁

I got deep in the weeds around discussions into the right way to shuffle an array in JavaScript to ensure randomness and efficiency. That all sounded great, but I wasn’t too worried about the randomness of my list.

Luckily, I found Nitin Patel’s post with a one-liner that worked for my use case:

array.sort(function (a, b) { return 0.5 — Math.random() })

Still, I wish JavaScript had a proper shuffle method. I mean shuffle()! Clearly I’m still getting used to the differences between Ruby and JavaScript.

--

--

Kevin Ebaugh

Community dude at @IFTTT. One time I caught a foul ball at Fenway. I'm sometimes confused with @ke$ha.