2

I am very new to JQuery, so sorry if this is a naive question. I am trying to randomize an array of 3 numbers, 35 times. Each time I shuffle the array of 3-numbers and write to console, it looks like a new shuffle is produced. However, when I add each new shuffling to an array and print the entirety of its contents, it seems that the array subsists of 35 copies of the last shuffle made.

Thanks in advance!

var arr2 = [0,1,2]; 

var seedArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]

var arr2AggregateArray = [];

for (i = 0; i < 35; i++) { 
    seed = seedArray[i];
    shuffle(arr2,seed);
    console.log(arr2);
    arr2AggregateArray[i] =  arr2;
    console.log(arr2); 
}

console.log(arr2AggregateArray);
1
  • please share copy of your shuffle function also. Commented Apr 21, 2016 at 5:37

1 Answer 1

5

This line:

arr2AggregateArray[i] =  arr2;

puts a reference to arr2 into arr2AggregateArray, not a copy. All 35 references refer to the same array:

+−−−−−−−−−−−−−−−−−−−−+  
| arr2AggregateArray |  
+−−−−−−−−−−−−−−−−−−−−+              +−−−−−−+
| 0:  *ref*          |−−−+−+−+−+−+−>| arr2 |
| 1:  *ref*          |−−/ / /   /   +−−−−−−+
| 2:  *ref*          |−−−/ /   /    | 0: 2 |
| 3:  *ref*          |−−−−/   /     | 1: 0 |
| ...                |       /      | 2: 1 |
| 34: *ref*          |−−−−−−/       +−−−−−−+
+−−−−−−−−−−−−−−−−−−−−+

You need to make a copy. In this case, since it just contains primitives (numbers), a shallow copy will do:

arr2AggregateArray[i] =  arr2.slice(0);

You haven't shown your shuffle function, so I've assumed it shuffles the array in-place. If it returns a new shuffled array, then you wouldn't need the slice above, but you'd just need to use shuffle's return value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.