Randomizing an array in Javascript

Posted: 09 Apr 2024. Last modified on 10-Apr-24.

This article will take about 1 minute to read.


Recently I decided to dust off my javascript skills and get to work relearning web development fundamentals. There’s a lot more to like now than there was back in 2015… but coming from Kotlin, I’ve been missing a lot of the built in standard library functionality. Most recently, the ability to shuffle a list.

What I’m looking for is essentially

val list = listOf(1,2,3,4,5)
println(list.shuffled())
// [3, 5, 4, 2, 1]

but it seems like javascript doesn’t have that built in yet.

Of course, I could use a library like Underscore.js. Underscore is like the missing standard library for JS collections-based functionality. However, if randomizing a list is the only functionality I need, it seems like a waste to add a whole dependency.

Reimplementing it isn’t that hard though.

const list = [1, 2, 3, 4, 5]
const shuffledList = list
    .map(value => ({ value, sort: Math.random() }))
    .sort((a, b) => a.sort - b.sort)
    .map(({ value }) => value)

In this example,

  1. we map the contents of the list to a wrapper object, which has a randomized sort id.
  2. We then sort the list with that sort id as the comparator, and
  3. map back to the original value.