How to shuffle an array using javascript
How to shuffle an array using javascript
Shuffling an array means we want to randomly rearranging the list or an array.
Using algorithms we use shuffle an array.
Algorithm:
Array =[11,12,13,14,15,16]
<button onclick="display()">
click
</button>
<script>
// Function for array shuffling
function ArrayShuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
//random number generate
var j = Math.floor(Math.random() * (i + 1));
var tempVar = array[i];
array[i] = array[j];
array[j] = tempVar;
}
return array;
}
//Showing result by this function
function display() {
var ary = [11,12,13,14,15,16]
var ary1 = ArrayShuffle(ary)
document.write("After shuffling Array: ", ary1)
}
</script>
Output
Before Shuffling
Array =[11,12,13,14,15,16]
After shuffling
After shuffling Array: 11,13,15,14,12,16
Algorithm:
This algorithms uses function that returns(random-0.5) as comparator to sort function.
Array =[11,12,13,14,15,16]
<button onclick="display()">
click
</button>
Output
Before Shuffling
Array =[11,12,13,14,15,16]
After shuffling
After shuffling Array: 12,15,16,11,13,14