Sorting an Array in Random Order – JavaScript

Welcome to codingle.com. Today I wanna show you how to sort numbers randomly using a JS tutorial for beginners; hope it would be useful for you.

before starting, you will launch your code in any code/text editor as your favorite. Then, you have to make a button to run the function everytime by clicking on it. Button will get an event with value of your functions name tha twe will create. Furthermore, you need to show up your result in preveiw by creating a div with any id name as I named demo. See the below code.

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>

var points = [40, 100, 1, 5, 25, 10];

document.getElementById("demo").innerHTML = points;

function myFunction1() { 

points.sort(function(a, b){return 0.5 - Math.random()});

document.getElementById("demo").innerHTML = points; 

}

</script>

I have created an array and gave some values are called to be viewed on #demo. sort() is an js function which represent the numbers and it is used another js function for the numbers ascending and decending. In addition, random() function is sorting number randomly.

Hope it would be useful for you just for fun I have posted it. Thanks

Murtaza

Agha Murtaza is a web designer and WordPress developer with over one year of experience. You can visit his business site here . Murtaza is the CEO of codingle.com. He also has an opinion on just about every subject. You can follow his rants on Twitter @murtaxa_n.