1. Use the sort method

For example, you can use the following method to sort an array: If a-b > -1, a comes before B; otherwise, A comes after B

Let arr =,12,34,5,6 [1]; arr.sort((a,b)=>a-b); console.log('arr',arr); // Return [1, 5, 6, 12, 34]Copy the code

So, to implement random array sorting, we can randomly generate a number between 0 and 1 to compare with 0.5, if greater than 0.5 return -1, otherwise return 1;

let arr=[1,'12m',34,'we','5uw','w6']; Const randomSort=()=>{return math.random () > 0.5? 1:1; } arr.sort(()=>randomSort()); console.log('arr',arr);Copy the code

2. Create a new array, insert a random element from the original array, and return the new array

let arr=[1,'12m',34,'we','5uw','w6']; Const randomSort=(origin_array)=>{let temp_array = origin_array.map(item=>item); let result_array=[]; While (temp_array.length) {// randomly generate [0,temp_array.length) between integers let randomIndex = Math.floor(Math.random()*temp_array.length); console.log('randomIndex',randomIndex);  result_array.push(temp_array[randomIndex]); temp_array.splice(randomIndex,1); } return result_array;  } const result = randomSort(arr); console.log('result',result);Copy the code

3. Random substitution of elements in array (similar to shuffle algorithm)

let arr=[1,'12m',34,'we','5uw','w6']; const randomSort=(origin_array)=>{ let len = origin_array.length; let temp=''; let randomIndex=0; for(let i=0; i<len; I ++) {// Generate [I,len) randomIndex = math.floor (math.random ()*(len-i)+ I); temp = origin_array[I];  origin_array[i] = origin_array[randomIndex]; origin_array[randomIndex] = temp; } return origin_array;  } let result = randomSort(arr); console.log('result',result)Copy the code