## DEV Community 👩‍💻👨‍💻 is a community of 964,423 amazing developers

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

Chris Bongers

Posted on • Originally published at daily-dev-tips.com

# Vanilla JavaScript Shuffle Array

Now and then, you need randomly to shuffle an array in `JavaScript`. There is a super-easy way of doing so. We can use the `sort()` method and pass a random number to it.

## JavaScript Shuffle Array

As mentioned in the introduction, we are going to be using the `sort` method.

This method, without any parameters, will sort an array in a natural way like 123 and abc.

See the following example:

``````var charArray = ['d', 'f', 'a', 'c', 'b', 'e'];
var numArray = [1, 5, 3, 2, 4];

console.log(charArray.sort());
// ["a", "b", "c", "d", "e", "f"]

console.log(numArray.sort());
// [1, 2, 3, 4, 5]
``````

As you can see the Arrays get normalised sorted. But we can also pass a specific argument which is what we are going to use to randomise the sort.

``````var rockPaperScissor = ['💎', '📄', '✂️'];
console.log(rockPaperScissor.sort(() => 0.5 - Math.random()));
``````

This will randomly shuffle the array let me explain in depth.

The `sort` function comes with a comparison between two elements, where element one is bigger than two. It will put the index lower or higher.

As for the `.5 - Math.random()` this will return a value between -0.5 and 0.5

So whenever the value is below 0, the element is placed before the one other element.

You can test this and see it in action on this Codepen.

See the Pen Vanilla JavaScript Shuffle Array by Chris Bongers (@rebelchris) on CodePen.

### Thank you for reading, and let's connect!

SavagePixie

It's worth noting that this won't work well for big arrays or if you need a thorough shuffle, as it isn't very likely that element are moved more than a couple positions.

Chris Bongers

You are absolutely right! Good mention indeed. Might have to update this

Serhii Pimenov

In Metro 4, I use this method

``````Array.prototype.shuffle = function () {
var currentIndex = this.length, temporaryValue, randomIndex;

while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = this[currentIndex];
this[currentIndex] = this[randomIndex];
this[randomIndex] = temporaryValue;
}
return this;
};
``````

Chris Bongers

Very nice that would be your normalized javascript solution as well.
Btw hadn't heard of Metro, but looks very cool

SavagePixie

The video may be old, but its main points are still valid:

• Code in benchmarking is rarely written like code in a real application
• Runtimes have all sorts of optimisations that aren't always easy to understand or bypass
• Best practice is to just write code that makes sense and profile your app if you run into performance issues

If you find that misleading, ¯_(ツ)_/¯

Chris Bongers

Hey there,

Thank you for the really extended answer.
I still find it weird you see everyone promoting the new functions like sort and map over basic loops because it reads easier or whatever the hip answer is here.

How do you feel about these very hyped functions?

I mean i love the simplicity of them, but performance-wise it may not always be the right solution.

As to your answer regarding the benchmarking, it is very specific. I love doing console.time logs but even they vary every run, like a lot. Of course the bigger the test, the better you see the actual result.

Chris Bongers

Hey,

wow nice results! so it's just Math.random in sort?
Any idea too why that is?

SavagePixie • Edited on

My guess would be that it's because, while in the other examples you're running the operation once per item in the array, with sort you're potentially running the operation several times per item, which increases the computation time.

That being said, you generally shouldn't trust benchmarking on jsperf

Chris Bongers

Very interesting though, would you mind if i do some testing of my own and maybe do another blog on the sort with bigger arrays and include some of your findings?