How to Randomly Arrange a JavaScript Array

Here is a way to randomly arrange an array in JS. The logic is we randomly select an element from the original array and put it in the first element of a new array. Then, randomly choose another element from the original array and put in the second element of a new array. We continue unitl we have selected all elements from the origial array. The new array is a randomly ordered array from another array.


A funtion to generate a randomly ordered array.

function getrandomorderedarray(a){   
   var newarray = [];
   var inputarray = [...a];
   var l = inputarray.length;
   for(let i = 0; i < l; i++){
	var xxx = inputarray.splice(Math.floor(Math.random()*(l-i)),1);
	newarray.push(xxx[0]);
   }
   return newarray;
};

Playground

1,2,3,4,5,6,7,8,9,10

We can also create an array of arrays of a same random order if the arrays are of the same length.

function getRandomOrderedArrayOfArrays(a){   
   var newarray = [];
   var inputarray = [];
   var l = a[0].length;

   a.forEach(x=>{
	inputarray.push([...x]);
        newarray.push([]);
   });	

   for(let i = 0; i < l; i++){
          var xxx = Math.floor(Math.random()*(l-i));
	  inputarray.forEach((x,i)=>{
		newarray[i].push(inputarray[i].splice(xxx,1)[0]);
 	  });	
   };
   return newarray;
};

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser