Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Randomly sorting an array

I just watched the Javascript Foundation, Methods: Part 1 video and have a question about sorting arrays.

Here is the code we write:

var my_array = [10, 44, 32, 100, 0, 44, 3, 4];

my_array.sort(function (a, b) {

    return Math.random() - 0.5;
});
console.log(my_array.toString());

I'm still not clear exactly how this sorts the elements of the array randomly, and why we need to return negative values (from -1.5 to 1.5).

I thought the Math.random return assigns random values from 0.0 to 1.0 for all elements in the array. Shouldn't this be enough to randomly sort the array? I understand the .sort method arranges the elements based on alphabetically ordering, not numberic, but shouldn't giving them new random values be enough even if these values are sorted alphabetically?

So I removed "- 0.5" from my code to see what happens and this is what I see in the console:

4,3,44,0,100,32,44,10

It just reversed the ordering of the array. And this is the result I get every time, it isn't random at all. I would like to understand why this happens.

1 Answer

Randomize the order of the array:

var my_array = [10, 44, 32, 100, 0, 44, 3, 4];
my_array.sort(function (a, b) {
    return 0.5 - Math.random();
});
console.log(my_array.toString());

The fundamental of how array.sort works is hard to discover and illustrate, you may get more information about the numerical order at Sorting a JavaScript array using array.sort()