Matthew Herbst
Matthew Herbst

Reputation: 31973

Why does my array not get reassigned when I shuffle it?

Update After further testing it does appear to work, however the console output is incorrect; both arrays still look exactly the same.


I am using the Fisher-Yates (Knuth) shuffle as described by this post (code near bottom): http://bost.ocks.org/mike/shuffle/

This code correctly shuffles an array of elements. I have tested this in console to verify. I am working on a project where I need to shuffle an array of arrays. This code correctly shuffles the array of arrays, as it is data agnostic.

However, when I try to assign the array to the new value, it does not change. For example:

data = [['1','2','3'],['4','5','6'],['7','8','9'],['10','11','12']];
data = shuffle(data); //Value of data does not change, even though shuffle works

When I do

shuffle(data);

in the console it returns a correctly shuffled array of arrays.

I have created this JSFiddle so you can see: http://jsfiddle.net/herbstmb/Ve24U/

If you look in your console clearly the shuffle works but the assignment fails.

Many thanks for any help understanding what's going on.

Upvotes: 0

Views: 121

Answers (1)

Juan Garcia
Juan Garcia

Reputation: 706

It does. Array are mutable. You get the same log in the console because they are both the shuffled result. You logged the unshuffled array first, but you inspected it after shuffled, then it is has changed. Check at the array values in the console and in the source, they differ.

Upvotes: 2

Related Questions