0

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [];
let index = Math.floor(Math.random() * arr1.length);

for(let i = 0; i < arr1.length; i++) {
    arr2.push(arr1[index]);
    do {
        index = Math.floor(Math.random() * arr1.length);
        console.log(arr2.includes(arr1[index])); //thís is to see the result
    } while (arr2.includes(arr1[index]))
}

console.log('arr2: ', arr2);

I want to make the new unordered array from the first array. But when I run this code, the loop becomes an infinite loop although the conditional is false. My question is the reason make the loop still running with the false conditional?

enter image description here

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 2
    Your code will hang inside the last do-while loop forever since at that point, every element has been pushed to the new array. Shuffling an array doesn't require a check like that if you remove the element from the original array (or a copy of it). –  Sep 17 '21 at 16:03
  • Add a `console.log()` in the outer loop and you'll see that the inner loop is not running when the condition is false. – Barmar Sep 17 '21 at 16:09
  • Make a simple copy of the original array and then perform a Fisher-Yates shuffle. – Pointy Sep 17 '21 at 16:09
  • See https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array for the correct ways to shuffle an array. – Barmar Sep 17 '21 at 16:10
  • I understand the problem. I will try again with the solution you gave me. Thanks you for all your help ☺️ – Mai Linh Sep 17 '21 at 16:23

0 Answers0