I have a array of 2N elements. For example,[1,2,3,4,5,6,7,8]
.
Now I want to separate it into an array of random pairs (no repeats).
The result may be:
[[1,3],[2,5],[4,8],[6,7]]
I try to code but I think it is not good. Any better ideas?
function arrSlice(arr) {
if (arr.length % 2 !== 0) return 0;
var
newArr = [],
//temp array.
tmpArr = [];
for (let i = 0; i < arr.length; i++) {
if (!tmpArr.includes(arr[i])) {
var rndIndex;
do {
rndIndex = Math.floor(Math.random() * (arr.length - (i + 1))) + (i + 1);
} while (tmpArr.includes(arr[rndIndex]));
newArr.push([arr[i], arr[rndIndex]]);
tmpArr.push(arr[i]);
tmpArr.push(arr[rndIndex]);
}
}
return newArr;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8]
console.log(arrSlice(arr));