Categories
JavaScript Answers

How to Shuffle an Array of Numbers with JavaScript?

Spread the love

With the sort method built into the JavaScript array objects, we can use it easily to sort arrays. The sort method takes a function that lets us compare 2 entries in the array to let us set the sort order between 2 elements based on the conditions that we specify.

The function that we pass into the sort method takes 2 parameters, the first is an element which we call a, and the second is an element which we call b, and we compare a and b to determine which should be sorted above the other in the array. The sort function expects a number to be returned by the callback.

If the value that’s returned by our function is negative, then a will be in an array index that’s lower than b. That is, a comes before b. If the number is positive, then b will come before a. If the function returns 0, then a and b will stay in their original position.

If we want to shuffle the array, we can just return a random number from it — the value of a or b will not have an impact on the sort. We can once again use the Math.random() method to help us generate a random return value for the function we pass into the sort method. We can write the following code to sort each entry in random order (shuffle the array):

let nums = [49, -151, 88, -133, -164, 78, 117, -25, 76, -40];
nums = nums.sort(() => {
  return Math.random() - 0.5
});
console.log(nums);

In the code above, our sort method has a function which generates a random number between -0.5 and 0.5, which means there’s a chance that each element either stays in place or gets shuffled, according to what the sort method will do depending on the return value.

The Math.random() only returns numbers between 0 and 1. However, we can easily make it more useful by extending it in the ways that we did above. We can specify a range between a minimum and a maximum number and Math.random() * (max — min) + min to generate a number between a range. Also, we can pass it into the callback function of the sort method by returning Math.random() — 0.5 to generate a number between -0.5 and 0.5, which means that it can be shuffled (or not) depending on the sign of the generated number and whether it’s 0 or not.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *