Every now and then you might need to shuffle some elements on your page, like in an online banking page you might have to display a virtual keypad which could be shuffled on demand, or on a tile game you’re most likely to have to shuffle the board. This problem usually boggles the mind of many people, but it has a very simple solution.

Let’s start with the basics. Javascript arrays have a method called sort(), which returns the sorted version of an array (note that it doesn’t actually modify the array itself), and receives a callback function as a parameter (called a predicate function), which in turn receives two parameters, referring to tuples of values from the array. The predicate is expected to compare those two values, and return a numeric value that tells the method which of the two values is supposed to rank first. Given that the two values are represented by a and b, the predicate would return a negative value when a comes before b, a positive value when b comes before a, and 0 if a and b match. Let’s look at an example.

Given an array of integers such as [ 3, 2, 8, 1, 5, 1 ], and given that we mean to sort it by ascending order, our predicate can be as follows: