The problem here is that you're adding a reference to the same array for each index. They're not all their own arrays- they're all the exact same one. Imagine there are two newscasters, each reporting on the same story. If the story changes, both newscasters will tell you the same update. That's what these arrays are doing. When you say something like arr1 = arr2, you're just saying that arr1 is now a newscaster for the same story/value- so changing the value associated with one of them changes both of them, and shuffling one of them shuffles both of them. To change this, you need to clone the array before assigning it to a new variable.
Change:
finalarr.push(arr);
to:
finalarr.push(arr.slice(0));
Using .slice(0)
on the array is a method to clone a shallow copy of the array (which will be sufficient for your code) so each one is actually its own value. Run this new version of your code here:
var arr = [1, 2, 3, 4];
finalarr = [];
for (i = 0; i <= 5; i++) {
arr.sort(function(a, b) {
return 0.5 - Math.random();
});
finalarr.push(arr.slice(0));
}
console.log(finalarr);
Personally, I choose to use randojs.com to grab shuffled arrays. It grabs a new, independent array each time you call randoSequence
, so no funny business to worry about with references. Your code would look like this with randojs:
var finalarr = [];
for (var i = 0; i <= 5; i++) finalarr.push(randoSequence(1, 4));
console.log(finalarr);
<script src="https://randojs.com/1.0.0.js"></script>