JSFiddle - React, Tailwind, and code Playground

by Glutamat

JavaScript

function shuffleUniquePos (arr) {
  var tmp = arr.slice(),ret= []; //create a shallow copy of the input array, and one for the new array
    for (;tmp.length;) { //let the loop run as long as we have elements in the array
        do { //Use a do while because we need i to be calcualted at least once
            var i = 0|Math.random() * tmp.length; //generate a random number in the range of the arrays size
        } while (ret[ret.length-1] === tmp[i]) //keep recalculating i as long as the last element of the return array matches the element in the tmp array at position i, or make sure there will not be the same element left from it (there is no right element because its the last one) 
       ret.push (tmp.splice (i,1)[0]);  //remove the element from tmp and push it into ret
    }
    return ret; //if all elements of tmp have been distributed return the new array
}

console.log (shuffleUniquePos ([1, 2, 3, 4, 5, 1, 6, 2, 7, 3, 8, 4, 9])) //[2, 8, 6, 7, 9, 3, 2, 1, 4, 5, 3, 1]