I want to randomly group an array with even elements, such as
[1,2,3,4,5,6,7,8]
output may have one result:
[[1,3],[2,5],[4,8],[6,7]]
I tried to write the code as follows:
function arrSlice(arr) {
if(arr.length % 2 !== 0) return 0;
var
newArr = [],
//
tmpArr = [];
for(let i=0;i<arr.length;iPP) {
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));
I am a novice at JS. I feel a little stiff in writing. I don"t know if there is a better implementation. Please ask Daniel for advice. Thank you